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>
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}.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With