使用 Spring 配置文件设置系统属性 [英] Set System Property With Spring Configuration File
问题描述
配置:
Spring 2.5、Junit 4、Log4j
log4j 文件位置由系统属性指定
Configuration:
Spring 2.5, Junit 4, Log4j
The log4j file location is specified from a system property
${log.location}
在运行时,系统属性设置为 -D java 选项.一切都很好.
At runtime, system property set with -D java option. All is well.
问题/我需要什么:
在单元测试时,系统属性未设置,文件位置未解析.
应用程序使用 Spring,想简单地配置 Spring 以设置系统属性.
更多信息:
要求仅用于配置.不能引入新的 Java 代码或进入 IDE.理想情况下,Spring 的一个属性配置实现可以处理这个问题——我只是一直找不到合适的组合.
More Info:
Requirement is for configuration only. Can't introduce new Java code, or entries into IDE. Ideally, one of Spring's property configuration implementations could handle this--I just haven't been able to find the right combination.
这个想法很接近,但是需要添加Java代码:
Spring SystemPropertyInitializingBean
This idea is close, but needs to add Java code:
Spring SystemPropertyInitializingBean
有什么帮助吗?任何想法表示赞赏.
Any help out there? Any ideas are appreciated.
推荐答案
你可以通过结合两个 MethodInvokingFactoryBeans
创建一个访问 System.getProperties 的内部 bean 和一个对内部 bean 获取的属性调用 putAll 的外部 bean:
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>
(当然,您可以只使用一个 bean 并以 System.setProperties() 为目标,但是您将替换现有的属性,这不是一个好主意.
(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"));
}
这是输出:
my.key: myvalue
my.key2: myvalue2
my.key3: myvalue3
java.io.tmpdir: C:DOKUME~1SEANFL~1LOKALE~1Temp
这篇关于使用 Spring 配置文件设置系统属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!