- 通过设定Enviroment的ActiveProfiles来决定当前context需要使用的配置环境,在开发中使用@Profile注解类或方法达到在不同情况下选择实例化不同的Bean
- 通过设定jvm的spring.profiles.active参数来设置环境
- Web项目设置servlet的context.paramter中
<!-- servlet2.5及以下 -->
<servlet>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</init-param>
</servlet>
/**
* servlet3.0及以上
*/
public class WebInit implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext contailer)throws ServletException{
container.setInitParameter("spring.profiles.default","dev");
}
}
示例Bean
/**
* @author Kevin
* @description
* @date 2016/6/30
*/
public class DemoBean {
private String content;
public DemoBean(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Profile配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author Kevin
* @description
* @date 2016/6/30
*/
@Configuration
public class ProfileConfig {
@Bean
// Profile为dev时实例化devDemoBean
@Profile("dev")
public DemoBean devDemoBean(){
return new DemoBean("from development profile");
}
@Bean
// Profile为prod时实例化prodDemoBean
@Profile("prod")
public DemoBean prodDemoBean(){
return new DemoBean("from production profile");
}
}
运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Kevin
* @description
* @date 2016/6/30
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 将profile设置为prod
context.getEnvironment().setActiveProfiles("prod");
// 注册Bean配置类
context.register(ProfileConfig.class);
// 刷新容器
context.refresh();
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}
结果
输出:from production profile