Set System Property With Spring Configuration File
You can achieve that with the combination of two MethodInvokingFactoryBeans
Create an inner bean that accesses System.getProperties and an outer bean that invokes putAll on the properties acquired by the inner bean:
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property
name="targetObject">
<!-- System.getProperties() -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
</property>
<property
name="targetMethod"
value="putAll" />
<property
name="arguments">
<!-- The new Properties -->
<util:properties>
<prop
key="my.key">myvalue</prop>
<prop
key="my.key2">myvalue2</prop>
<prop
key="my.key3">myvalue3</prop>
</util:properties>
</property>
</bean>
(You could of course use just one bean and target System.setProperties(), but then you'd be replacing existing properties which is not a good idea.
Anyway, here's my little test method:
public static void main(final String[] args) {
new ClassPathXmlApplicationContext("classpath:beans.xml");
System.out.println("my.key: "+System.getProperty("my.key"));
System.out.println("my.key2: "+System.getProperty("my.key2"));
System.out.println("my.key3: "+System.getProperty("my.key3"));
// to test that we're not overwriting existing properties
System.out.println("java.io.tmpdir: "+System.getProperty("java.io.tmpdir"));
}
And here's the output:
my.key: myvalue
my.key2: myvalue2
my.key3: myvalue3
java.io.tmpdir: C:\DOKUME~1\SEANFL~1\LOKALE~1\Temp\
There was a request in the comments for a Spring 3 example on how to do this.
<bean id="systemPrereqs"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" value="#{@systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<!-- The new Properties -->
<util:properties>
<prop key="java.security.auth.login.config">/super/secret/jaas.conf</prop>
</util:properties>
</property>
</bean>