2013-11-28 45 views
0

我有使用提供一個PropertyPlaceholderConfigurer現有的基於XML的彈簧配置如下:彈簧@PropertySource與環境類型轉換

<context:property-placeholder location="classpath:my.properties" /> 

    <bean id="myBean" class="com.whatever.TestBean"> 
    <property name="someValue" value="${myProps.value}" /> 
    </bean> 

myprops.value=classpath:configFile.xml和關於「someValue中」屬性的setter接受org.springframework.core .io.Resource

這工作正常 - PPC將自動在字符串值和資源之間進行轉換。

現在我試圖用Java配置和@PropertySource註解如下:

@Configuration 
@PropertySource("classpath:my.properties") 
public class TestConfig { 

    @Autowired Environment environment; 

    @Bean 
    public TestBean testBean() throws Exception { 
     TestBean testBean = new TestBean(); 
     testBean.setSomeValue(environment.getProperty("myProps.value", Resource.class)); 
     return testBean; 
    } 

} 

春節環境類的的getProperty()方法提供過載,支持轉換爲不同的類型,這是我以前用過,然而,這並不默認支持屬性轉換爲資源:

Caused by: java.lang.IllegalArgumentException: Cannot convert value [classpath:configFile.xml] from source type [String] to target type [Resource] 
    at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:81) 
    at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:370) 
    at config.TestConfig.testBean(TestConfig.java:19) 

綜觀底層源代碼,環境實現使用一個PropertySourcesPropertyResolver,這反過來使用DefaultConversionService這隻能記錄非常基本的轉換器。

所以我有兩個問題:
1)我怎樣才能得到這個支持轉換爲資源?
2)爲什麼我需要當原始PPC爲我做這個?

回答

0

我已經解決了這個如下。

我意識到從資源包獲取屬性然後在bean上設置屬性之間存在區別--Spring將在使用相關PropertyEditor(ResourceEditor)設置屬性時進行轉換。因此,我們必須手工完成此步驟:

@Configuration 
@PropertySource("classpath:my.properties") 
public class TestConfig { 

    @Autowired Environment environment; 

    @Bean 
    public TestBean testBean() throws Exception { 
     ResourceEditor editor = new ResourceEditor(); 
     editor.setAsText(environment.getProperty("myProps.value")); 
     TestBean testBean = new TestBean(); 
     testBean.setSomeValue((Resource)editor.getValue()); 
     return testBean; 
    } 

} 

但是這並留下爲什麼由環境內部使用的DefaultConversionService不會自動拿起屬性編輯器的懸而未決的問題。這可能是用做:

https://jira.springsource.org/browse/SPR-6564

0

我正面臨同樣的問題,事實證明,context:property-placeholder不僅加載屬性文件,而且還聲明處理所有文件的特殊bean org.springframework.context.support.PropertySourcesPlaceholderConfigurer,例如,解決${...}屬性並將其替換。

爲了固定它,你只需要創建它的實例:

@Configuration 
public class TestConfig { 

    @Autowired Environment environment; 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer configurer(){ 
     PropertySourcesPlaceholderConfigurer postProcessor = new PropertySourcesPlaceholderConfigurer(); 
     postProcessor.setLocation(new ClassPathResource("my.properties")); 
     return postProcessor; 
    } 

... 

注意,你需要刪除@PropertySource("classpath:my.properties")註解。

+0

感謝n1ckolas,我已經見過它做這樣 - 因爲你說它是相當於XML。但是,我認爲這正是@PropertySource註釋應該避免的內容。 –