我有使用提供一個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爲我做這個?
感謝n1ckolas,我已經見過它做這樣 - 因爲你說它是相當於XML。但是,我認爲這正是@PropertySource註釋應該避免的內容。 –