如何在应用程序上下文中读取系统环境变量?
我想要这样的东西:
<util:properties id="dbProperties"
location="classpath:config_DEV/db.properties" />或
<util:properties id="dbProperties"
location="classpath:config_QA/db.properties" />取决于环境的不同。
我可以在我的应用程序上下文中使用这样的东西吗?
<util:properties id="dbProperties"
location="classpath:config_${systemProperties.env}/db.properties" />其中,实际val是根据系统环境变量设置的
我使用的是Spring3.0
发布于 2010-10-19 14:07:33
检查this article。它为您提供了几种方法,通过支持外部属性的PropertyPlaceholderConfigurer (通过systemPropertiesMode属性)。
发布于 2010-10-19 14:02:13
很接近:o) Spring3.0添加了Spring Expression Language。您可以使用
<util:properties id="dbProperties"
location="classpath:config_#{systemProperties['env']}/db.properties" />结合使用java ... -Denv=QA应该可以解决您的问题。
另请注意@yiling的评论:
为了访问系统环境变量,也就是操作系统级变量,我们可以简单地在EL中使用"systemEnvironment“而不是"systemProperties”。像
#{systemEnvironment['ENV_VARIABLE_NAME']}
一样
发布于 2015-04-20 18:09:57
现在你可以把
@Autowired
private Environment environment;在您的@Component、@Bean等中,然后通过Environment类访问这些属性:
environment.getProperty("myProp");@Bean中单个属性的
@Value("${my.another.property:123}") // value after ':' is the default
Integer property;是方便的@ConfigurationProperties beans的另一种方式:
@ConfigurationProperties(prefix="my.properties.prefix")
public class MyProperties {
// value from my.properties.prefix.myProperty will be bound to this variable
String myProperty;
// and this will even throw a startup exception if the property is not found
@javax.validation.constraints.NotNull
String myRequiredProperty;
//getters
}
@Component
public class MyOtherBean {
@Autowired
MyProperties myProperties;
}注意:只需记住在设置新的环境变量后重新启动eclipse。
https://stackoverflow.com/questions/3965446
复制相似问题