And*_*708 5 java spring spring-mvc spring-el
我需要在我的配置文件之一中获取以下系统属性:-Dspring.profiles.active="development". 现在我看到无数人建议这可以用 Spring 表达式语言来完成,但我无法让它工作。这是我尝试过的(加上许多变体)。
@Configuration
@ComponentScan(basePackages = { ... })
public class AppConfig {
@Autowired
private Environment environment;
@Value("${spring.profiles.active}")
private String activeProfileOne;
@Value("#{systemProperties['spring.profiles.active']}")
private String activeProfileTwo;
@Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
Resource[] resources = {
new ClassPathResource("application.properties"),
new ClassPathResource("database.properties")
// I want to use the active profile in the above file names
};
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setLocations(resources);
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}
}
Run Code Online (Sandbox Code Playgroud)
所有的属性都是NULL. 如果我尝试访问任何其他系统属性,也会发生同样的情况。我可以通过调用毫无问题地访问它们System.getProperty("spring.profiles.active"),但这不太好。
我发现的许多示例都将其配置PropertySourcesPlaceholderConfigurer为也搜索系统属性,所以也许这就是它不起作用的原因。但是,这些示例在 Spring 3 和 XML 配置中,设置了类中不再存在的属性。也许我必须调用该setPropertySources方法,但我不完全确定如何配置它。
不管怎样,我发现了多个例子,表明我的方法应该有效。相信我,我四处搜寻了很多。怎么了?
Environment只需自动装配 Spring接口的实例,就像您实际所做的那样,然后询问活动环境是什么:
@Configuration
public class AppConfig {
@Autowired
private Environment environment;
@Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
List<String> envs = Arrays.asList(this.environment.getActiveProfiles());
if (envs.contains("DEV")) {
// return dev properties
} else if (envs.contains("PROD")) {
// return prod properties
}
// return default properties
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4382 次 |
| 最近记录: |