如何向应用程序上下文添加属性

时间:2012-02-15 13:20:25

标签: java spring

我有一个独立应用程序,这个应用程序计算一个值(属性),然后启动一个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:

<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"/>

这是一个Spring 3.0应用程序。

4 个答案:

答案 0 :(得分:23)

在Spring 3.1中,您可以实现自己的PropertySource,请参阅:Spring 3.1 M1: Unified Property Management

首先,创建自己的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;
    }
}

现在在刷新应用程序上下文之前添加此PropertySource

AbstractApplicationContext appContext =
    new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml"}, false
    );
appContext.getEnvironment().getPropertySources().addLast(
   new CustomPropertySource()
);
appContext.refresh();

从现在开始,您可以在Spring中引用您的新房产:

<context:property-placeholder/>

<bean class="com.example.Process">
    <constructor-arg value="${myCalculatedProperty}"/>
</bean>

也适用于注释(记得添加<context:annotation-config/>):

@Value("${myCalculatedProperty}")
private String magic;

@PostConstruct
public void init() {
    System.out.println("Magic: " + magic);
}

答案 1 :(得分:8)

您可以将计算值添加到系统属性中:

System.setProperty("placeHolderName", myCalculatedProperty);

答案 2 :(得分:3)

如果您在控制示例中创建的ApplicationContext,则可以始终添加BeanRegistryPostProcessor以将第二个PropertyPlaceholderConfigurer添加到上下文中。它应该有ignoreUnresolvablePlaceholders="true"order="1",并且只使用Properties对象解析自定义计算属性。所有其他属性应由PropertyPlaceholderConfigurer从应该具有order="2"的XML中解析。

答案 3 :(得分:0)

您的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();
}
相关问题