【发布时间】:2013-11-28 15:23:46
【问题描述】:
我有一个现有的基于 xml 的 spring 配置,使用 PropertyPlaceholderConfigurer,如下所示:
<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' 属性的设置器接受 org.springframework.core.io.Resource。
这很好 - PPC 将自动在字符串值和资源之间转换。
我现在正在尝试使用 Java Config 和 @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;
}
}
Spring Environment 类的 getProperty() 方法提供了一个重载来支持转换为不同的类型,我使用过,但是默认情况下不支持将属性转换为 Resource:
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)
查看底层源代码,Environment 实现使用 PropertySourcesPropertyResolver,而后者又使用 DefaultConversionService,而这只注册了非常基本的转换器。
所以我有两个问题:
1)我怎样才能得到这个来支持资源的转换?
2) 当原始 PPC 为我执行此操作时,我为什么需要这样做?
【问题讨论】:
标签: spring type-conversion spring-annotations