一 点睛
Profile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定不同,例如数据库的配置)。
通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。
在开发中使用@Profile注解类或者方法,达到不同情况下选择实例化不同的Bean。
二 实战
1 编写DemoBean
package com.wisely.highlight_spring4.ch2.profile;
public class DemoBean {
private String content;
public DemoBean(String content) {
super();
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
2 Profile配置
package com.wisely.highlight_spring4.ch2.profile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev") //为dev时,实例化devDemoBean
public DemoBean devDemoBean() {
return new DemoBean("from development profile");
}
@Bean
@Profile("prod") //为prod时,实例化prodDemoBean
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}
3 编写主类
package com.wisely.highlight_spring4.ch2.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("dev"); //将活动的Profile设置为prod
context.register(ProfileConfig.class);//后置注册Bean配置类,不然会报Bean未定义的错误
context.refresh(); //刷新容器
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}
三 运行
from development profile