ProFile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)
(1) 通过设定Environment的ActiveProFiles来设定当前context需要使用的配置环境。在开发中使用@ProFile注解类或者方法,达到在不同情况下选择实例化不同的Bean。
(2) 通过设定jvm的spring.profiles.active参数来设置配置环境。
(3) Web项目设置在Servlet的context parameter中。
servlet2.5及以下:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 在DispatcherServlet参数中设置profile的默认值,active同理 -->
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>development</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
servlet 3.0及以上:
public class WebInit implements WebApplicationIntitializer {
@override
public void onStartup(ServletContext container) throws ServletException {
container.setInitParameter(spring.profiles.default", "dev");
}
}
示例:
(1)示例bean
package com.wisely.highlight_spring.ch2.profile;
public class DemoBean {
public DemoBean(String content) {
super();
this.content = content;
}
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
(2) Profile 配置
package com.wisely.highlight_spring.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") //Profile为dev时实例化devDemoBean
public DemoBean devDemoBean() {
return new DemoBean("from development profile");
}
@Bean
@Profile("prod") //profile为prod时实例化prodDemoBean
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}
(3) 运行
package com.wisely.highlight_spring.ch2.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod"); //先将活动的profile设置为dev
context.registerBean(ProFileConfig.class); //后置注册Bean配置类,不然会报bean未定义的错误
context.refresh(); //刷新容器
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}
结果如下:
将context.getEnvironment().setActiveProFiles("prod")修改为 context.getEnvironment().setActiveProFiles("dev"),效果如下所示: