0

我们使用的是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));
    }
}

现在我们将它移到 spring 3.1.2 并且可以帮助我判断 spring 提供了一些新的 API 来更有效地完成它吗?

4

1 回答 1

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>

BTW. in Spring 3.0 the bean class is: PropertyPlaceholderConfigurer (see this blog http://www.baeldung.com/2012/02/06/properties-with-spring/)

于 2013-01-18T07:07:44.910 回答