Spring注解@Profile与@Conditional
1、@Profile注解
1.1、使用场景:
项目中使用多个数据库配置时,根据生产环境与测试环境的不同需要进行不同的配置,
如果每次都进行配置文件的修改,不方便也容易出错。
Spring为我们提供了@Profile注解实现加载指定的Bean实现简单的控制。
1.2、配置profile bean
1.2.1、注解方式
Spring3.2之后实现能够在方法级别上添加@Profile注解代码如下:
@Bean
@Profile("mysql_develop")
public DataSource druidDataSourceForMySQL() {
DruidDataSource database = new DruidDataSource();
database.setDriverClassName(environment.getProperty("jdbc.mysql.driverClassName"));
database.setUrl(environment.getProperty("jdbc.mysql.url"));
database.setUsername(environment.getProperty("jdbc.mysql.username"));
database.setPassword(environment.getProperty("jdbc.mysql.password"));
database.setDefaultAutoCommit(false);
database.setTimeBetweenEvictionRunsMillis(3600000);
database.setMinEvictableIdleTimeMillis(3600000);
database.setInitialSize(1);
return database;
}
1.2.2、配置文件方式
<beans profile="mysql_develop">
//待加载的bean
</beans>
1.3、激活 profile
激活profile的方式:在spring初始化加载的地方添加
'spring.profiles.active'或者
'spring.profiles.default'两个独立的属性。
通过读取profiles的值来激活指定value相同的@Profile注解下的Bean。
value值可以设置为多个之间用,隔开。
设置属性的方式:
1. applicationContext参数
2. 环境变量(添加到配置文件中)
3. DispatcherServlet初始化参数
4. 测试类中@ActiveProfiles注解上
例如:
在context中
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>mysql_develop,dev</param-value>
</context-param>
使用测试类时:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={PresistenceTestConfig.class})
@ActiveProfiles("dev")
public class Test {
...
}
在环境变量中
在加载的配置文件中添加:
spring.profiles.active=dev
2、@Conditional
2.1、使用场景
控制注解是否生效 例如:
@Conditional(SchedulingConfigCondition.class)
@PropertySource(value = {"classpath:task.properties"})
@Service("CreateESIndexTask.run")
@Lazy(false)
在SchedulingConfigCondition类上实现Condition接口,重写matches方法,matches方法返回值为true表示创建当前Bean,返回false表示不创建当前bean。
例子:
public class SchedulingConfigCondition implements Condition{
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return check( conditionContext, annotatedTypeMetadata);
}