0

I have a peculiar requirement of setting the value of some bean from system environment variable , is this thing possible in spring ?

Pseudo code

<bean id="connectionFactory"
    class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="testhost" />
        <property name="username" value="$SystemEnv.RabbitUserName" />
        <property name="password" value="$SystemEnv.RabbitPassword" />
    </bean>

Now these RabbitUserName and RabbitPassword are externalized in some environmental variable which is outside .war file .

Is there any elegant way to achieve the same in spring ?

Akshat
  • 515
  • 2
  • 10
  • 24
  • possible duplicate of [PropertyPlaceholderConfigurer and environment variables in .properties files](http://stackoverflow.com/questions/10324702/propertyplaceholderconfigurer-and-environment-variables-in-properties-files) – Sachin Gorade Apr 28 '15 at 09:00
  • Akshat, please select a correct answer to this question. – Ungeheuer Mar 02 '21 at 00:12

2 Answers2

2

To get the System Environment Variable you can use this for the value:

#{ systemEnvironment['RabbitUserName'] }

The #{ systemProperties['RabbitUserName'] } mentioned in another answer won't give you a System Environment Variable, rather it will read a Java system property ie, those things you can set on the command line when starting the JVM, eg:

java -DRabbitUserName="reisen" etc...

However, this is probably a better choice of place for a connection credential than an environment variable, as, for example, you can then configure it differently for different launch configurations and it is also slightly less exposed than an environment value - which all the other applications also have full visibility on.

For more information on the difference between environent variables and system properties see Java system properties and environment variables

These are examples of the Spring Expression Language (SpEL), and you can also use it with annotation metadata, for example

@Value("#{ systemEnvironment['RabbitUserName'] }")

For more information on SpEL you can take a look at the Spring reference here: https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/expressions.html

Andrew H
  • 159
  • 8
0

This should work.

<bean id="connectionFactory"
    class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="testhost" />
        <property name="username" value="#{systemProperties['RabbitUserName']}" />
        <property name="password" value="#{systemProperties['RabbitPassword']}" />
    </bean>
Jens
  • 60,806
  • 15
  • 81
  • 95