2010-10-19 73 views
84

如何在应用程序上下文中读取系统环境变量?如何在Spring应用程序上下文中读取系统环境变量

我想是这样的:这取决于environement

<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是基于系统环境变量

我使用Spring 3.0

回答

23

是的,你可以做<property name="defaultLocale" value="#{ systemProperties['user.region']}"/>例如设定。

变量系统属性是预定义的,请参阅6.4.1 XML based configuration

85

您正在关注:o) Spring 3.0增加了Spring Expression Language。 您可以使用

<util:properties id="dbProperties" 
    location="classpath:config_#{systemProperties['env']}/db.properties" /> 

java ... -Denv=QA结合应该解决您的问题。

还要注意通过@yiling评论:

为了访问系统环境变量,即OS级别 变量AMOE评论,我们可以简单地用“systemEnvironment” 而不是“systemProperties” EL。像 #{systemEnvironment['ENV_VARIABLE_NAME']}

+0

什么是java ... -Denv = QA的含义? – 2012-01-18 14:47:50

+2

您设置了一个java系统属性值。你可以像'assert System.getProperty(“env”)==“QA”那样在代码中读取这个值;' – amra 2012-01-20 17:14:08

+0

我认为这个答案是不正确的,这不允许读取系统环境变量(即OS级别的变量'export'等),它只允许读取Java系统属性。 – amoe 2013-11-15 13:24:48

8

在您的bean定义中,请确保包含“searchSystemEnvironment”并将其设置为“true”。如果您使用它来构建文件路径,请将其指定为file:/// url。

因此,举例来说,如果你有位于

/testapp/config/my.app.config.properties 

一个配置文件,然后设置环境变量,像这样:

MY_ENV_VAR_PATH=/testapp/config 

和您的应用程序可以加载该文件使用一个bean定义,就像这个:

eg

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"> 
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
    <property name="searchSystemEnvironment" value="true" /> 
    <property name="searchContextAttributes" value="true" /> 
    <property name="contextOverride" value="true" /> 
    <property name="ignoreResourceNotFound" value="true" /> 
    <property name="locations"> 
     <list> 
      <value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value> 
     </list> 
    </property> 
</bean> 
+2

现在我该如何读取java中加载的属性? – Bhuvan 2013-05-17 06:05:36

5

对于我的用例,我只需要访问系统属性,但在未定义的情况下提供默认值。

这是你如何做到这一点:

<bean id="propertyPlaceholderConfigurer" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
    <property name="searchSystemEnvironment" value="true" /> 
</bean> 
<bean id="myBean" class="path.to.my.BeanClass"> 
    <!-- can be overridden with -Dtest.target.host=http://whatever.com --> 
    <constructor-arg value="${test.target.host:http://localhost:18888}"/> 
</bean> 
6

使用Spring EL可以eis example写如下

<bean id="myBean" class="path.to.my.BeanClass"> 
    <!-- can be overridden with -Dtest.target.host=http://whatever.com --> 
    <constructor-arg value="#{systemProperties['test.target.host'] ?: 'http://localhost:18888'}"/> 
</bean> 
+0

关于默认值的好提示 – 2017-08-16 17:32:33

1

这是你如何做到这一点:

<bean id="systemPrereqs" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" scope="prototype"> 
      <property name="targetObject" value="#{@systemProperties}" /> 
      <property name="targetMethod" value="putAll" /> 
      <property name="arguments"> 
        <util:properties> 
         <prop key="deployment.env">dev</prop> 
        </util:properties> 
      </property> 
    </bean> 

但要记住spring首先被加载,然后它将加载这个Bean MethodInvokingFactoryBean。所以如果你正在尝试使用这个测试用例,那么请确保你使用depends-on。对于例如在这种情况下

如果你正在使用它的主类中更好使用你的pom.xml作为

<systemProperty> 
    <name>deployment.env</name> 
    <value>dev</value> 
</systemProperty> 
27

现在来设置该属性可以把

@Autowired 
private Environment environment; 

在您的@Component,@Bean等,然后通过Environment类访问属性:

environment.getProperty("myProp"); 

对于单个属性@Bean

@Value("${my.another.property:123}") // value after ':' is the default 
Integer property; 

另一种方式是得心应手@ConfigurationProperties豆:

@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; 
} 

注:请记住设置一个新的环境变量

+0

env变量是否也可以通过'Environment'接口访问? – 2016-12-11 18:06:16

+0

@NikhilSahu是的,他们是。你可以像查询'java.lang.System'一样使用相同的键来访问它们,例如,如果要获得操作系统类型,你可以使用'env.getProperty(“os.name”)'假设'env'是'org的实例.springframework.core.env.Environment'。 – Ninetou 2017-06-27 18:15:36

-2

要获得系统变量,下面的代码SimPy中使用的值之后重新启动Eclipse:

System.getenv("property-name"); 
1

您可以在属性文件中提到你的变量属性和定义特定于环境的属性文件,如local.properties,production.propertied等。

现在基于环境,这些属性文件中的一个可以在启动时调用的侦听器中读取,如ServletContextListener。

属性文件将包含各种键的环境特定值。

样本 “local.propeties”

db.logsDataSource.url=jdbc:mysql://localhost:3306/logs 
db.logsDataSource.username=root 
db.logsDataSource.password=root 

db.dataSource.url=jdbc:mysql://localhost:3306/main 
db.dataSource.username=root 
db.dataSource.password=root 

样本“生产。属性”

db.logsDataSource.url=jdbc:mariadb://111.111.111.111:3306/logs 
db.logsDataSource.username=admin 
db.logsDataSource.password=xyzqer 

db.dataSource.url=jdbc:mysql://111.111.111.111:3306/carsinfo 
db.dataSource.username=admin 
[email protected] 

对于使用这些属性文件,你可以利用的资源为下面提到

 PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); 
     ResourceLoader resourceLoader = new DefaultResourceLoader(); 

     Resource resource = resourceLoader.getResource("classpath:"+System.getenv("SERVER_TYPE")+"DB.properties"); 
     configurer.setLocation(resource); 
     configurer.postProcessBeanFactory(beanFactory); 

SERVER_TYPE可以被定义为本地和生产环境的相应值的环境变量。

通过这些更改,应用程序Context.xml将进行以下更改

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
    <property name="url" value="${db.dataSource.url}" /> 
    <property name="username" value="${db.dataSource.username}" /> 
    <property name="password" value="${db.dataSource.password}" /> 

希望这会有所帮助。

4

申报财产占位如下

<bean id="propertyPlaceholderConfigurer" 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
    <property name="locations"> 
     <list> 
      <value>file:///path.to.your.app.config.properties</value> 
     </list> 
    </property> 
</bean> 

那么可以说你想读System.property("java.io.tmpdir")为Tomcat豆或豆然后添加在你的属性如下文件:

tomcat.tmp.dir=${java.io.tmpdir} 
0

感谢@Yiling。这是一个暗示。

<bean id="propertyConfigurer" 
     class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"> 

    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
    <property name="searchSystemEnvironment" value="true" /> 
    <property name="locations"> 
     <list> 
      <value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value> 
      <value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value> 
      <value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value> 
     </list> 
    </property> 
</bean> 

之后,你应该有一个名为'FILE_PATH'的环境变量。确保在创建该环境变量后重新启动机器。

相关问题