1、@Profile用于多个环境间切换,以生产(pro)和测试(dev)环境为例:
创建环境信息类:
public class Enviroment {
private String name;
private String context;
public Enviroment(String name, String context) {
this.name = name;
this.context = context;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
创建测试和生产环境:
@ComponentScan("com.it.app.profile")
public class Config {
//创建测试环境dev
@Bean()
@Profile("dev")
public Enviroment enviromentDev() {
Enviroment enviroment = new Enviroment("dev", "init dev enviroment");
System.out.println(enviroment.getContext());
return enviroment;
}
//创建生产环境pro
@Bean()
@Profile("pro")
public Enviroment enviromentPro() {
Enviroment enviroment = new Enviroment("pro", "init pro enviroment");
System.out.println(enviroment.getContext());
return enviroment;
}
}
用户切pro和dev环境:context.getEnvironment().setActiveProfiles(“dev”)。
也可以设置多个环境
context.getEnvironment().setActiveProfiles(“pro”,“dev”)
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// context.getEnvironment().setActiveProfiles("pro","dev"); 可以设置多个环境共存
//设置为dev测试环境
context.getEnvironment().setActiveProfiles("dev");
context.register(Config.class);
context.refresh();
}
}
执行结果:
init dev enviroment