您的位置:首页 > 编程语言 > Java开发

Spring注解驱动开发-自动装配@Profile根据环境注册bean

2019-03-22 17:32 891 查看

Profile:
Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能;
开发环境、测试环境、生产环境;
数据源:(/A)(/B)(/C);
@Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
1)、加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
2)、写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
3)、没有标注环境标识的bean在,任何环境下都是加载的;

package com.edward.config;
@PropertySource(value = {"classpath:/db.properties"})
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware {

//用了三种方式读取配置文件中的值
//1.@Value("${db.user}")
//2.在创建bean的时候通过参数
//3.通过实现EmbeddedValueResolverAware接口读取
@Value("${db.user}")
private  String user;

private StringValueResolver valueResolver;

private String driverClass;

@Profile("test")
@Bean
public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {

ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/it");
return dataSource;
}

@Profile("dev")
@Bean
public DataSource dataSourceDev(@Value("${db.password}") String password) throws PropertyVetoException {

ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/it");
return dataSource;
}

@Profile("prod")
@Bean
public DataSource dataSourceProd(@Value("${db.password}") String password) throws PropertyVetoException {

ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/it");
return dataSource;
}

@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
this.valueResolver = stringValueResolver;
driverClass = valueResolver.resolveStringValue("${db.driverclass}");
}
}

1. 可以用-Dspring.profiles.active=test指定环境

2.也可以在代码中指定环境、

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("prod");
applicationContext.register(MainConfigOfProfile.class);
applicationContext.refresh();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: