对于 Spring Boot 应用程序,即使使用 YAML 文件也可以轻松运行
spring:
profiles: dev
property: this is a dev env
---
spring:
profiles: prod
property: this is a production env
---
但是,对于 Spring MVC 应用程序,它需要更多的工作。看看this link
基本上,它涉及2个步骤
- 在 servlet 上下文中获取 Spring Profile
如果您在服务器上设置了配置文件并希望它在您的应用程序中检索它,您可以使用 System.getProperty 或 System.getenv 方法。
如果没有找到配置文件,这里是获取配置文件并将其默认为本地配置文件的代码。
private static final String SPRING_PROFILES_ACTIVE = "SPRING_PROFILES_ACTIVE";
String profile;
/**
* In local system getProperty() returns the profile correctly, however in docker getenv() return profile correctly
* */
protected void setSpringProfile(ServletContext servletContext) {
if(null!= System.getenv(SPRING_PROFILES_ACTIVE)){
profile=System.getenv(SPRING_PROFILES_ACTIVE);
}else if(null!= System.getProperty(SPRING_PROFILES_ACTIVE)){
profile=System.getProperty(SPRING_PROFILES_ACTIVE);
}else{
profile="local";
}
log.info("***** Profile configured is ****** "+ profile);
servletContext.setInitParameter("spring.profiles.active", profile);
}
- 要访问 application-dev.properties,现在说您需要使用
类级别的@Profile("dev")
以下代码将获取 application-dev.properties 和 common.properties
@Configuration
@Profile("dev")
public class DevPropertyReader {
@Bean
public static PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource("properties/common.properties"), new ClassPathResource("properties/application-dev.properties") };
ppc.setLocations(resources);
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}
要访问说 application-prod.properties,您必须在类级别使用 @Profile("prod")。更多详情可以found here