1.概念
Profile为不同环境下使用不同的配置提供了支持(开发环境和生产环境)
2.使用
(1)通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。具体注解@Profile
(2)通过设定jvm的spring.profiles.active参数来设置配置环境
(3)web项目设置在Servlet的context parameter中
3.示例
package highlight_spring4.chi2.profile;
public class DemoProfileService {
private String content;
public DemoProfileService(String content){
super();
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package highlight_spring4.chi2.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 DemoProfileService devDemoProfileBean(){
return new DemoProfileService("from delelopment profile");
}
@Bean
@Profile("prod")
public DemoProfileService prodDemoProfileBean(){
return new DemoProfileService("from production profile");
}
}
package highlight_spring4.chi2.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 运行类
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProfileConfig.class);
context.getEnvironment().setActiveProfiles("prod");
context.register(ProfileConfig.class);//后置注册Bean配置类,不然会报Bean未定义
//context.refresh();
DemoProfileService demoProfileService = context.getBean(DemoProfileService.class);
System.out.println(demoProfileService.getContent());
context.close();
}
}