java – 在Spring Framework中使用SPeL读取系统属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 在Spring Framework中使用SPeL读取系统属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1986字,纯文字阅读大概需要3分钟。
内容图文
我需要在我的一个配置文件中获取以下系统属性:-Dspring.profiles.active =“development”.现在我看到无数人都认为这可以通过Spring Expression Language完成,但我无法让它工作.这是我尝试过的(加上其中的许多变化).
@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;
}
}
所有属性都是NULL.如果我尝试访问任何其他系统属性,也会发生同样的情况.通过调用System.getProperty(“spring.profiles.active”),我可以毫无问题地访问它们,但这不是很好.
我发现的许多示例都将PropertySourcesPlaceholderConfigurer配置为也搜索系统属性,因此可能这就是它无效的原因.但是,这些示例在Spring 3和XML配置中,设置了类中不再存在的属性.也许我必须调用setPropertySources方法,但我不完全确定如何配置它.
无论哪种方式,我发现了多个示例,表明我的方法应该有效.相信我,我搜索了很多.怎么了?
解决方法:
只需自动装配一个Spring的Environment interface实例,就像你实际做的那样,然后询问活动环境是什么:
@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
}
}
内容总结
以上是互联网集市为您收集整理的java – 在Spring Framework中使用SPeL读取系统属性全部内容,希望文章能够帮你解决java – 在Spring Framework中使用SPeL读取系统属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。