2012-11-12 53 views
2

属性占位符继承我想我们的港口自定义属性占位符使用Spring的新Environment支持,但我无法弄清楚如何让我们目前的占位符魔法做什么。在Spring 3.1

我想是对的属性文件默认一堆从classpath中读取,然后让这些属性覆盖(覆盖)由一堆属性文件从别的地方。 我不希望将所有属性替换为另一组文件中设置的属性。

到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*.propertiesfile://blah/*.properties

现在看来,而不是我的Resource[]工厂我可以自定义PropertySources并将其连接到PlaceholderConfig,但似乎它提供没有价值,然后上述。

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

如何从与出定制源硬编码的来源之一叠加特性不必重写/实现一堆类?

+0

有点类似:http://stackoverflow.com/questions/8587489/how-to-set-active-spring-3-1-environment-profile-via-a-properites-file-and-not-v –

回答

0

加班我慢慢地将我的原始配置解析代码移植到新的Spring环境中。

我谈论它在这个StackOverflow的问题:How can I easily switch between environment specific runtime configuration with IntelliJ?

你可以看到code as a Gist并使用我用我的大部分的Spring项目的相同的配置逻辑。

对于单元测试可悲的是,上下文初始化器只能在Spring 3.2中使用。请参阅updated @ContextConfiguration Annotation。我不得不使用旧的自定义属性占位符来使用Spring 3.1及更早版本的项目。