我有一个独立应用程序,这个应用程序计算一个值(属性),然后启动一个Spring Context.我的问题是如何将该计算属性添加到spring上下文中,以便我可以像从属性文件(@Value("${myCalculatedProperty}")
)中加载的属性一样使用它?
稍微说明一下
public static void main(final String[] args) {
String myCalculatedProperty = magicFunction();
AbstractApplicationContext appContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//How to add myCalculatedProperty to appContext (before starting the context)
appContext.getBean(Process.class).start();
}
Run Code Online (Sandbox Code Playgroud)
applicationContext.xml中:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:*.properties" />
</bean>
<context:component-scan base-package="com.example.app"/>
Run Code Online (Sandbox Code Playgroud)
这是一个Spring 3.0应用程序.
Tom*_*icz 23
在Spring 3.1中,您可以实现自己的PropertySource
,请参阅:Spring 3.1 M1:统一属性管理.
首先,创建自己的PropertySource
实现:
private static class CustomPropertySource extends PropertySource<String> {
public CustomPropertySource() {super("custom");}
@Override
public String getProperty(String name) {
if (name.equals("myCalculatedProperty")) {
return magicFunction(); //you might cache it at will
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
现在PropertySource
在刷新应用程序上下文之前添加它:
AbstractApplicationContext appContext =
new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml"}, false
);
appContext.getEnvironment().getPropertySources().addLast(
new CustomPropertySource()
);
appContext.refresh();
Run Code Online (Sandbox Code Playgroud)
从现在开始,您可以在Spring中引用您的新房产:
<context:property-placeholder/>
<bean class="com.example.Process">
<constructor-arg value="${myCalculatedProperty}"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
也适用于注释(记得添加<context:annotation-config/>
):
@Value("${myCalculatedProperty}")
private String magic;
@PostConstruct
public void init() {
System.out.println("Magic: " + magic);
}
Run Code Online (Sandbox Code Playgroud)
您可以将计算值添加到系统属性:
System.setProperty("placeHolderName", myCalculatedProperty);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41419 次 |
最近记录: |