【问题标题】:Properties Placeholder Inheritance in Spring 3.1Spring 3.1 中的属性占位符继承
【发布时间】:2012-11-01 10:02:12
【问题描述】:

我正在尝试使用 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 环境,因此不适用于集成测试(我不想在我的每一个单元测试中添加注释来告诉它环境是我可以像以前一样设置系统属性)。

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

【问题讨论】:

标签: java spring spring-environment


【解决方案1】:

随着时间的推移,我慢慢将原来的配置解析代码移植到了新的 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 及更早版本的项目,我必须使用旧的自定义属性占位符。

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2014-03-10
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2016-02-22
    • 2013-05-05
    相关资源
    最近更新 更多