Profile在不同环境下使用不同的配置提供了支持。
DemoBean.java
public class DemoBean {
private String context;
public DemoBean(String context) {
super();
this.context = context;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
ProfileConfig.java
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev") // Profile为 dev时,实例化devDemoBean
public DemoBean devDemoBean(){
return new DemoBean(" from delelopment profile");
}
@Bean
@Profile("prod") // Profile为prod时,实例化prodDemoBean
public DemoBean prodDemoBean(){
return new DemoBean(" from production profile");
}
}
Main.java
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("prod"); // 先将激活的Profile设置为prod
ctx.register(ProfileConfig.class); // 后置注册Bean配置类,不然为报Bean未定义的错误
ctx.refresh(); // 刷新容器
DemoBean demoBean = ctx.getBean(DemoBean.class);
System.out.println(demoBean.getContext());
ctx.close();
}
}
运行结果: