Spring 3.1中的属性占位符继承

时间:2012-11-12 22:49:09

标签: java spring spring-environment

我正在尝试使用Spring的新Environment支持来移植我们的自定义属性占位符,但我无法弄清楚如何获得我们当前占位符魔术的功能。

我想要的是从类路径中读取一组默认的属性文件,然后通过来自其他地方的一堆属性文件覆盖这些属性(覆盖)。 我不希望所有属性都替换为另一组文件中设置的属性。

在Spring 3.1之前

<bean class="com.snaphop.spring.ConfigResourcesFactoryBean" id="customConfig">
    <property name="parameterName" value="customConfig"/>
    <property name="defaultResources" value="classpath*:META-INF/spring/*.properties"/>
</bean>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="customPropertyPlaceholder">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
    <property name="locations" ref="customConfig"/>
</bean>

现在ConfigResourcesFactoryBean只是一个神奇的FactoryBean,它找到要提供给占位符配置的资源列表:

public class ConfigResourcesFactoryBean implements FactoryBean<Resource[]> {
// Loads a bunch of Resources (property files) 
// based on System.property/Environment variable "customConfig"
}

现在,customConfig可能设置为-DcustomConfig=file://blah/*.propertiesexport customConfig=file://blah/*.properties

目录blah中的属性仅覆盖classpath*:META-INF/spring/*.properties的子集。因此,工厂返回的Resource[]将分别是classpath*:META-INF/spring*.properties后跟file://blah/*.properties的联合。

现在它出现而不是我的Resource[]工厂我可以制作一个自定义PropertySources并将其连接到PlaceholderConfig,但似乎它没有提供上述值。

我不能使用ApplicationContextInitializer,因为我发誓这只适用于Servlet环境,因此无法使用集成测试(我不想在每个单元测试中添加注释来告诉它当我可以像以前一样设置系统属性时环境是什么。)

如何使用自定义源从硬编码源覆盖属性,而不必覆盖/实现一堆类?

1 个答案:

答案 0 :(得分:0)

加班我慢慢将原始配置解析代码移植到新的Spring Environment处理方式。

我在StackOverflow问题中谈到它:How can I easily switch between environment specific runtime configuration with IntelliJ?

您可以看到code as a Gist并使用我用于大多数Spring项目的相同配置逻辑。

对于单元测试,Context Initializer实际上只适用于Spring 3.2。请参阅updated @ContextConfiguration Annotation。对于使用Spring 3.1及更早版本的项目,我不得不使用旧的自定义属性占位符。

相关问题