一. 点睛
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>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</init-param>
</servlet>
在Servlet3.0
及以上使用方式如下:
package org.light4j.sping4.usually.profile;
import javax.servlet.ServletContext;
import org.springframework.web.WebApplicationInitializer;
public class WebInit implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext container) throws ServletException {
container.setInitParameter("spring.profiles.default","dev");
}
}
二.示例
1.示例Bean
package org.light4j.sping4.usually.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 org.light4j.sping4.usually.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") //①
public DemoBean devDemoBean() {
return new DemoBean("from development profile");
}
@Bean
@Profile("prod") //②
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}
代码解释:
①
Profile
为dev
时实例化devDemoBean
②Profile
为prod
时实例化prodDemoBean
3. 运行
package org.light4j.sping4.usually.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("dev"); //①
context.register(ProfileConfig.class);//②
context.refresh(); //③
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}
代码解释:
① 先将活动的
Profile
设置为prod
② 后置注册Bean
配置类,不然会报Bean
未定义的错误。
③ 刷新容器
运行结果如下图所示:
将context.getEnvironment().setActiveProfiles("prod")
修改为context.getEnvironment().setActiveProfiles("dev")
,
运行结果如下图所示:
4. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » Spring4.x常用配置(四):Spring Profile