Profile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。
bean:
public class ProfileBean {
private String content;
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
};
public ProfileBean(String content) {
this.content = content;
}
}
配置类:
@Configuration
@ComponentScan("com.demo02.profile")
public class ProfileConfig {
@Bean
@Profile("dev")
public ProfileBean depDemo() {
return new ProfileBean("development 开发环境");
}
@Bean
@Profile("prod")
public ProfileBean prodDemo() {
return new ProfileBean("production 生产环境");
}
}
@Profile("dev"):表示当前为dev时,才会执行该方法。
@Profile("prod"):表示当前为prod时,才会执行该方法。
测试运行:
public class App {
public static void main(String[] args) {
//1、因为配置类,需重新指定模式(开发或是生产等),所以在新建annotation时,不用加载配置类。
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//2、使用Environment来指定当前运行的模式,指定的值必须和@Profile注解中自定义的值匹配。否则都不执行。
context.getEnvironment().setActiveProfiles("prod");
//3、指定模式后,再注册Bean
context.register(ProfileConfig.class);
//4、刷新容器,注册生效。
context.refresh();
ProfileBean bean = context.getBean(ProfileBean.class);
System.out.println(bean.getContent());
context.close();
}
}
注意:
1、需要调整配置类,在创建Annotation时,就不用指定配置类。
2、根据Environment中的setActiveProfiles("指定模式"),来指定当前运行的模式,指定模式需要与配置类中设置的值对应。
3、指定模式后,需要注册配置类
4、最后刷新容器,注册的配置类才会生效。
5、可在类上加@ActiveProfiles("dev")注解替代Environment.setActiveProfiles("dev") 。