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

2022-09-02 09:18:29

我有一个独立的应用程序,这个应用程序计算一个值(属性),然后启动一个弹簧上下文。我的问题是如何将计算出的属性添加到弹簧上下文中,以便我可以像从属性文件()加载的属性一样使用它?@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();
}

应用上下文.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"/>

这是一个弹簧3.0应用程序。


答案 1

在 Spring 3.1 中,您可以实现自己的,请参阅:Spring 3.1 M1:统一属性管理PropertySource

首先,创建您自己的实现: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();

从现在开始,您可以在春季参考您的新房产:

<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);
}

答案 2

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

System.setProperty("placeHolderName", myCalculatedProperty);

推荐