Profile为不同环境下使用不同配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。
通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。在开发中使用@Profile注解类或者方法,达到在不同环境下选择实例化不同的Bean;
示例代码
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.fk")
public DruidDataSource fkDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.log")
public DruidDataSource logDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@Profile({"dev", "guard", "prod", "test"})
@ConfigurationProperties("spring.datasource.druid.ynlog")
public DruidDataSource ynLogDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "dataSource")
@Profile({"dev", "guard", "prod", "test"})
@Primary
public DynamicDataSource dataSource(DruidDataSource fkDataSource, DruidDataSource logDataSource , DruidDataSource ynLogDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceNames.FK, fkDataSource);
targetDataSources.put(DataSourceNames.LOG, logDataSource);
targetDataSources.put(DataSourceNames.YNLOG, ynLogDataSource);
return new DynamicDataSource(fkDataSource, targetDataSources);
}
@Bean(name = "dataSource")
@Profile({"prodqd"})
@Primary
public DynamicDataSource dataSourceQd(DruidDataSource fkDataSource, DruidDataSource logDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceNames.FK, fkDataSource);
targetDataSources.put(DataSourceNames.LOG, logDataSource);
return new DynamicDataSource(fkDataSource, targetDataSources);
}
}
上述代码的意思是
如果加上 @Profile({"dev","test"}) 注解 , spring.profile.active = dev /test 时才会实例化该Bean,否则不会实例化