How do I read JVM arguments in the Spring applicationContext.xml

jinxed picture jinxed · Apr 8, 2011 · Viewed 46.9k times · Source

I have a JSF web application with Spring and I am trying to figure out a way to reference the JVM arguments from the applicationContext.xml. I am starting the JVM with an environment argument (-Denv=development, for example). I have found and tried a few different approaches including:

<bean id="myBean" class="com.foo.bar.myClass">
  <property name="environment">
    <value>${environment}</value>
  </property>
</bean>

But, when the setter method is invoked in MyClass, the string "${environment}" is passed, instead of "development". I have a work around in place to use System.getProperty(), but it would be nicer, and cleaner, to be able to set these values via Spring. Is there any way to do this?

Edit: What I should have mentioned before is that I am loading properties from my database using a JDBC connection. This seems to add complexity, because when I add a property placeholder to my configuration, the properties loaded from the database are overridden by the property placeholder. I'm not sure if it's order-dependent or something. It's like I can do one or the other, but not both.

Edit: I'm currently loading the properties using the following configuration:

<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc.mydb.myschema"/> 
</bean>

<bean id="props" class="com.foo.bar.JdbcPropertiesFactoryBean">
    <property name="jdbcTemplate">
        <bean class="org.springframework.jdbc.core.JdbcTemplate">
            <constructor-arg ref="myDataSource" />
        </bean>
    </property>
</bean>

<context:property-placeholder properties-ref="props" />

Answer

Ralph picture Ralph · Apr 8, 2011

You can use Spring EL expressions, then it is #{systemProperties.test} for -Dtest="hallo welt"

In your case it should be:

<bean id="myBean" class="com.foo.bar.myClass">
  <property name="environment">
    <value>#{systemProperties.environment}</value>
  </property>
</bean>

The # instead of $ is no mistake!

$ would refer to place holders, while # refers to beans, and systemProperties is a bean.


May it is only a spelling error, but may it is the cause for your problem: In the example for your command line statement you name the variable env

(-Denv=development, for example...

But in the spring configuration you name it environment. But both must be equals of course!