Profile
为在不同环境下使用不同的配置提供了支持(如开发环境和生产环境下的数据库配置不同).
-
- 通过设定 Environment 的 ActiveProfiles 来设定当前 context 需要使用的配置环境.在开发中使用 @Profile 注解类或者方法,达到不同环境下选择实例化不同的 Bean.
- 通过设定 jvm 的 spring.profiles.active 参数来设置配置环境.
- Web 项目设置在 Servlet 的 context parameter 中.
示例:
package com.pangu.profile;
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;
}
}
package com.pangu.profile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @ClassName: ProfileConfig
* @Description: TODO(这里用一句话描述这个类的作用)
* @author etfox
* @date 2018年6月25日 上午9:00:58
*
* @Copyright: 2018 www.etfox.com Inc. All rights reserved.
*/
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev")
public DemoBean devDemoBean(){
return new DemoBean("from development profile");
}
@Bean
@Profile("prod")
public DemoBean proDemoBean(){
return new DemoBean("from production profile");
}
}
package com.pangu.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext application =
new AnnotationConfigApplicationContext();
application.getEnvironment().setActiveProfiles("prod");//设置 profile
application.register(ProfileConfig.class);//注册配置类
application.refresh();//刷新容器
DemoBean demoBean = (DemoBean)application.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
application.close();
}
}
运行结果:
八月 23, 2018 9:14:43 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5d099f62: startup date [Thu Aug 23 09:14:43 CST 2018]; root of context hierarchy
from production profile
八月 23, 2018 9:14:43 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5d099f62: startup date [Thu Aug 23 09:14:43 CST 2018]; root of context hierarchy