Aubergine Aubergine - 5 months ago 25
Java Question

How to inject environmental variables inside spring xml configuration?

AWS talks about

System.getProperty("JDBC_CONNECTION_STRING")
in http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.managing.html after we set up our environmental variables. All great except I can't call
System.getProperty
inside my Spring XML configuration code nor I can call for resource bundle shortcuts since resources bundle itself has to extract somehow these environmental variables to serve them. Could you kindly help me please to convert this example config to use environmental variables ? :-)

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://secrethost:007/whois?autoReconnect=true" />
<property name="username" value="bond" />
<property name="password" value="abuginsidemistycorner" />
<property name="initialSize" value="100" />

<property name="minEvictableIdleTimeMillis">
<value>300000</value>
</property>

<property name="timeBetweenEvictionRunsMillis">
<value>60000</value>
</property>

<property name="maxIdle" value="20" />
</bean>


I was not able to understand what do people do here:

Can I use an Environment variable based location for Spring FileSystemResource? which would work for recent spring version?

Answer

First add a <context:property-placeholder .. /> element to your configuration.

<context:property-placeholder />

Then simply use placeholders in your config.

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${JDBC_CONNECTION_STRING}" />
    <property name="username" value="bond" />
    <property name="password" value="abuginsidemistycorner" />
    <property name="initialSize" value="100" />
    <property name="minEvictableIdleTimeMillis" value="30000" />
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <property name="maxIdle" value="20" />
</bean>

Make sure that the placeholder names match your variables you have setup.

Comments