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

Ral*_*lph 15 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();
}
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)


Yaz*_*ber 8

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

System.setProperty("placeHolderName", myCalculatedProperty);
Run Code Online (Sandbox Code Playgroud)

  • 但要注意这种方式您可以使用启动参数(即-DplaceHolderName = someEnvSpecificValue)禁用从应用程序外部轻松覆盖此属性的可能性.我认为添加使用系统属性的可能性来处理特定于环境的值,并且还有其他可能性将您的自定义属性添加到上下文中,即注册多个"PropertyPlaceholderConfigurer". (2认同)