我有使用提供一个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注释应该避免的内容。 –