如何将属性添加到应用程序上下文 [英] How to add Properties to an Application Context

查看:129
本文介绍了如何将属性添加到应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个独立应用程序,该应用程序计算一个值(属性),然后启动一个Spring Context. 我的问题是如何将计算出的属性添加到spring上下文中,以便像从属性文件(@Value("${myCalculatedProperty}"))加载的属性一样使用它?

I have a Standalone Application, this application calculates a value (Property) and then starts a Spring Context. My question is how can I add that calculated property to the spring context, so that I can use it like properties loaded from a property file (@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:

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应用程序.

It is a Spring 3.0 Application.

推荐答案

在Spring 3.1中,您可以实现自己的PropertySource,请参见:

In Spring 3.1 you can implement your own PropertySource, see: Spring 3.1 M1: Unified Property Management.

首先,创建您自己的PropertySource实现:

First, create your own PropertySource implementation:

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:

Now add this PropertySource before refreshing the application context:

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

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

From now on you can reference your new property in Spring:

<context:property-placeholder/>

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

还可以使用注释(请记住添加<context:annotation-config/>):

Also works with annotations (remember to add <context:annotation-config/>):

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

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

这篇关于如何将属性添加到应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆