まず、この文書の注釈の春公式な説明を見てください:
@Profile
注釈を使用すると、コンポーネントは、1つまたは複数の指定されたプロファイルがアクティブな場合、登録の対象であることを示すことができます
現在の環境に応じて、この表記法、活性化およびスイッチングコンポーネントのダイナミックレンジ
私たちが開発したときに接続の開発に、例を実行する前に、いくつかの知識を持っても組み合わせたデータベースの開発環境、テスト接続のテスト環境、本番環境が接続されているが、異なる環境で使用される、本番データベースですデータベースには、ソースがそれを注入しどのようにデータを動的に切り替えるには、どう違うのですか?
説明するための構成クラス
まず、コンフィギュレーション・クラスを見てMainConfigProfile
クラス
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;
import com.atguigu.bean.Yellow;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* Profile:
* Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能;
*
* 开发环境、测试环境、生产环境;
* 数据源:(/A)(/B)(/C);
*
*
* @Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
*
* 1)、加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
* 2)、写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
* 3)、没有标注环境标识的bean在,任何环境下都是加载的;
*/
@PropertySource("classpath:/dbconfig.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
@Value("${db.user}")
private String user;
private StringValueResolver valueResolver;
private String driverClass;
@Bean
public Yellow yellow(){
return new Yellow();
}
@Profile("test")
@Bean("testDataSource")
public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); // 测试库
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Profile("dev")
@Bean("devDataSource")
public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_crud"); // 开发库
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Profile("prod")
@Bean("prodDataSource")
public DataSource dataSourceProd(@Value("${db.password}")String pwd) throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/scw_0515"); // 生产库
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
// TODO Auto-generated method stub
this.valueResolver = resolver;
driverClass = valueResolver.resolveStringValue("${db.driverClass}");
}
}
コンフィギュレーション・クラスでは、我々は、テスト環境、開発環境、本番環境に対応し、3豆を注入しました。
ユーザー、パスワード、ドライバー、URL:私たちは、注入のデータソースは、四ダイヤモンドが必要であることを知っています。
注意:ここでは、私たちがここにいると、同じデータベースに接続されていない3つの環境はURLのみを区別するために。各環境でのURLが異なっています。
他の3つのパラメータは、私たちはクラスのパスに配置されておりdb.properties
、以下のように
db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver
予備知識は、さまざまな使用に、ここに私の研究と合わせdb.properties
た値
リソースファイルの使用がロードされ、この用法は見つけることができます:春と@PropertySourceは@valueプロパティの割り当てを使用しています
@PropertySource("classpath:/dbconfig.properties")
それはどのようにあります
dataSource.setUser(user);
dataSource.setPassword(pwd);
それを割り当てるこれらの2つの方法?
まず、構築します
private String user;
属性は、属性@Value("${db.user}")
、その後、
dataSource.setUser(user);
値を取得します。
第二に、それ、
public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{...}
私たちは、パラメータ追加する前に、メソッドにパラメータを追加@Value("${db.password}")
リソースファイルから缶をdb.properties
このパラメータに割り当てられ、値を取得します
概要:上記の@valueの使用は、上記のリンクを参照してください。
ここにいた、我々は、リソースファイルdriverClassを取得するには、別の言い方をします
私たちは、実装できるEmbeddedValueResolverAware
インターフェイスは、インターフェイスは、我々は春の根本的な機能を使用する方法に利用できる多くの意識がある春。
ここでEmbeddedValueResolverAware
値リゾルバは、達成するための抽象メソッドでインターフェースを実装します
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
// TODO Auto-generated method stub
this.valueResolver = resolver;
driverClass = valueResolver.resolveStringValue("${db.driverClass}");
}
コンテナが起動すると、このメソッドが呼び出されます、
我々は、すなわち、受信されたプロセスパラメータの値の属性を定義しますStringValueResolver resolver
private StringValueResolver valueResolver;
そして、解析
driverClass = valueResolver.resolveStringValue("${db.driverClass}");
そして、我々のカスタムdriverClassプロパティに割り当てられています。だから、このプロパティには、リソースファイルの値になるだろう
そして、あまり@Profile関係が、良い評価上記
加えて、我々はと呼ばれる定義された構成クラスにまだあるyellow
豆。
テスト、および対応する環境を活性化させます
まず、我々はすべて参加していない@Profile
コメントを
テスト、我々は試験法と呼ばれるコンソール出力を、見て
package com.atguigu.test;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.atguigu.bean.Yellow;
import com.atguigu.config.MainConfigOfProfile;
public class IOCTest_Profile {
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}
}
mainConfigOfProfile
yellow
testDataSource
devDataSource
prodDataSource
クラス構成が容器に注入されるIOCビーン自体の全てを見ることができる含んでいます。
これで、すべて@Profileコメントを開きます
例えば、我々は今あるdev
だけでアクティブにする方法であり、開発環境の下で@Bean("devDataSource")
、それのコンポーネントを?
私たちは、テストクラスを書きます
package com.atguigu.test;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.atguigu.bean.Yellow;
import com.atguigu.config.MainConfigOfProfile;
public class IOCTest_Profile {
//1、使用命令行动态参数: 在虚拟机参数位置加载 -Dspring.profiles.active=test
@SuppressWarnings("resource")
//2、代码的方式激活某种环境;
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext();
//1、创建一个applicationContext
//2、设置需要激活的环境
applicationContext.getEnvironment().setActiveProfiles("dev"); // 这里可以写多个值,
//3、注册主配置类
applicationContext.register(MainConfigOfProfile.class);
//4、启动刷新容器
applicationContext.refresh();
String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
for (String string : namesForType) {
System.out.println(string);
}
Yellow bean = applicationContext.getBean(Yellow.class);
System.out.println(bean);
applicationContext.close();
// AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);
// String[] definitionNames = applicationContext.getBeanDefinitionNames();
// for (String name : definitionNames) {
// System.out.println(name);
// }
}
}
印刷コンソール:
devDataSource
com.atguigu.bean.Yellow@27ce24aa // 没有被@Profile修饰。
観察見つけることができ、実際に、開発環境のみBeanがIOCコンテナを注入され、
@Profileコメントを有効にする別の方法があります。
試験方法1:
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}
その後、プロセスを実行しますが、パラメータが時間を実行している仮想マシンを追加する必要があります。私たちは、バック=環境、カンマで区切られた複数の値を有効にする必要があります。
-Dspring.profiles.active =テスト
それをプリントアウト:
mainConfigOfProfile
yellow
testDataSource //测试环境被注入
クラスで@Profile注釈、
私たちは、コンフィギュレーションクラスに追加し、そのままの構成クラス残ります@Profile("prod")
我々は、(上述の前)試験方法を実行し、Beanクラスの構成を表すコンソール出力は、容器内に注入されていないありません、
このように考えていることがあります。クラスにマーク@Profileノート、あなたは環境の活性化を指定しない場合、クラス全体の自然な構成がロードされません、設定されたクラスビーン(イエローとして、ノートを@Profileていなくても、場合)、またそれを容器に注入され、
我々は、それが作動した後の環境を修正する必要があると同じように?(環境をアクティブにする方法、以前の記事を参照してください)
コンソールのプリントアウト
mainConfigOfProfile
yellow
prodDataSource
これは、我々が同じで期待したものは明らかです。
ヒント
環境が起動されていない場合、@Profile("default")
つまり、デフォルトはデフォルトの設定で、有効化されます。