Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Accessing environment variables inside applicationConfig.xml

Tags:

spring

I would like to set my db credentials and other secret values as part of environment variables. Is there a way of accessing the environment variables inside applicationConfig.xml

I tried <property name="username" value="#{systemEnvironment['db_username']}" />. However this did not work. Am I missing something?

Many were telling me how to access values from a properties file. I need to access the environment variable directly.

My code is as follows:-

<context:component-scan base-package="org.dhana.*" />

    <context:annotation-config />

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>



    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="xxxx" />
        <property name="username" value="${db_username}" />
        <property name="password" value="xxxxx" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
like image 709
Coding the beast Avatar asked Mar 15 '23 04:03

Coding the beast


2 Answers

You may have to set searchSystemEnvironment value to make it work.

<bean id="propertyPlaceholderConfigurer"   
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
</bean>

Then, we should able to access ${MY_ENV_VAR}.

like image 125
Rakesh Goyal Avatar answered Mar 16 '23 17:03

Rakesh Goyal


You can use environment variables using ${} For example if you want to add a config file which location depends on a environment variable named 'env_config_path' you can use this:

  <context:property-placeholder location="file:${env_config_path}/configuration.properties" />

I do not recomend you to use environment variables for concrete values, i think it's a better aproach to use a file pointed by a environment variable, as in my example.

You can force the environment variable value when loading your java program using a paremeter like the following:

-Denv_resource_path="/Users/mylogin/work/myproject/development_environment_resources" 
like image 23
Ricardo Vila Avatar answered Mar 16 '23 16:03

Ricardo Vila