6-profile
2018-10-02 本文已影响0人
中_中_
profile提供了一种在特定环境下运行特定配置的功能,例如开发时的测试数据库和正式生产上的数据库,通过激活不同的profile达到控制不同数据库连接的目的。
任何@component和@configuration都能用来注解@profile,以确定加载不同配置的时机,在application.properties当中添加spring.profiles.active=dev/test。
spring.profiles.active :确定激活那个配置
spring.profiles.include:无条件的添加激活配置
例如:
spring.profiles: prod
spring.profiles.include: proddb,prodmq
当prod被激活时,proddb和promq也会被激活。
测试
新建两个使用@configuration注解的类,并实现InitializingBean接口
@Configuration
@Profile(value={"product"})
public class MyProfileProduct implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println(this.getClass().getName()+" have bean created");
}
}
@Configuration
@Profile(value={"test"})
public class MyProfileTest implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println(this.getClass().getName()+" have bean created");
}
}
在application.properties中添加如下配置项:
spring.profiles.active=product
启动程序,观察哪个属性类被成功创建。

使用SpringApplication.setAdditionalProfiles(profiles)也能达到同样的效果;配置文件内容不变,在程序启动前添加如下内容:
application.setAdditionalProfiles("test");
观察输出:两个配置配置类均可以被创建。
