2012-11-12 100 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及更早版本的項目。