2013-11-28 119 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注释应该避免的内容。 –