如何将属性添加到应用程序上下文
我有一个独立应用程序,这个应用程序计算一个值(属性),然后启动一个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(); }
applicationContext.xml中:
这是一个Spring 3.0应用程序。
在Spring 3.1中,您可以实现自己的PropertySource
,请参阅: Spring 3.1 M1:统一属性管理 。
首先,创建自己的PropertySource
实现:
private static class CustomPropertySource extends PropertySource { public CustomPropertySource() {super("custom");} @Override public String getProperty(String name) { if (name.equals("myCalculatedProperty")) { return magicFunction(); //you might cache it at will } return null; } }
现在在刷新应用程序上下文之前添加此PropertySource
:
AbstractApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml"}, false ); appContext.getEnvironment().getPropertySources().addLast( new CustomPropertySource() ); appContext.refresh();
从现在开始,您可以在Spring中引用您的新房产:
也适用于注释(记得添加
):
@Value("${myCalculatedProperty}") private String magic; @PostConstruct public void init() { System.out.println("Magic: " + magic); }
您可以将计算值添加到系统属性:
System.setProperty("placeHolderName", myCalculatedProperty);
如果您在示例中控制ApplicationContext
的创建,则可以始终添加BeanRegistryPostProcessor
以将第二个PropertyPlaceholderConfigurer
添加到上下文中。 它应该ignoreUnresolvablePlaceholders="true"
和order="1"
并使用Properties
对象仅解析自定义计算属性。 所有其他属性应由PropertyPlaceholderConfigurer
从应具有order="2"
的XML中解析。
您的myCalculatedProperty
必须包含在您的一个属性文件中(由Spring propertyPlaceholderConfigurer
注入)。
编辑:只需使用setter,就像这样
public static void main(final String[] args) { String myCalculatedProperty = magicFunction(); AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Process p = appContext.getBean(Process.class); p.setMyCalculatedProperty(myCalculatedProperty); p.start(); }