Profile
Profile为在不同环境使用不同的配置提供了支持(开发环境下的配置和生成环境下的配置肯定是不同的。比如数据库的位置)
1.通过设定Environment的ActiveProfiles来设定当前contest需要使用的配置环境。
在开发中使用@Profile注解类或者方法,达到不同情况下选择实例化不同的Bean
2.通过设定jvm的spring.profiles.active参数来设置配置环境
3.Web项目设置在Servlet的contest parameter中 (翻译鄙视参数)
servlet2.5中
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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(ServletContest container) throws ServletException{
container.setInitParameter("spring.profiles.default","dev");
}
}
Profile配置
@Configuration
public class devDemoBean {
/**
* Profile为dev时 实例化devDemoBean
* @return
*/
@Bean
@Profile("dev")
public DemoBean devDemoBean(){
return new DemoBean("from development profile");
}
/**
* Profile为prod时 实例化prodDemoBean
* @return
*/
@Bean
@Profile("prod")
public DemoBean prodDemoBean(){
return new DemoBean("from production profile");
}
}
示例Bean
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;
}
}
运行
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 先将活动的Profile设置为prod
context.getEnvironment().setActiveProfiles("prod");
//后置注册Bean配置类。不让回报未定义的错误
context.register(devDemoBean.class);
//刷新容器
context.refresh();
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}