spring 3.1.2 RELEASE,<context:property-placeholder> usage </context:property-placeholder>

时间:2013-01-18 06:58:42

标签: spring

我们使用的是spring 2.5,我们想要添加以确保我的属性应该从环境config_path=C:/application.properties提供,或者从类路径的默认位置覆盖

所以我们这样做了 的applicationContext.xml

<bean class="com.test.utils.ExtendedPropertySourcesPlaceholderConfigurer">
    <property name="overridingSource" value="file:${config_path}/application.properties"/>
    <property name="locations" value="classpath*:META-INF/*-config.properties" />
</bean>

ExtendedPropertySourcesPlaceholderConfigurer代码

public class ExtendedPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Resource overridingSource;

    public void setOverridingSource(Resource overridingSource) {
        this.overridingSource = overridingSource;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MutablePropertySources sources = ((ConfigurableApplicationContext) applicationContext).getEnvironment().getPropertySources();
        if (overridingSource == null) {
            return;
        }
        sources.addFirst(new ResourcePropertySource(overridingSource));
    }
}

现在我们将这个转移到春季3.1.2并且可以帮助我解决天气问题,春天提供了一些新的API,以更有效的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

Spring 3.1引入了新的Environment AbstractionPropertySource Abstraction (两个链接都显示了SpringSource博客文章)

但我认为你不需要在spring 3.0或3.1中覆盖它

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:application-config.properties</value>
            <value>file:${user_config_path}/application-config.properties</value>
        </list>
    </property>
    <property name="localOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
</bean>

顺便说一句。在Spring 3.0中,bean类是:PropertyPlaceholderConfigurer(参见此博客http://www.baeldung.com/2012/02/06/properties-with-spring/