Spring-Profile 根据配置环境的 不同,实例化不同的实例

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,否则不会实例化 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值