2012-10-25 149 views
2

我希望公开一个Properties Spring bean,其值已经通过典型的属性扩展机制进行了扩展。我正在使用Spring 3.1。让我离题了。PropertyFactoryBean属性扩展

考虑以下属性文件:

server.host=myhost.com 
service.url=http://${server.host}/some/endpoint 

和Spring XML配置文件中的这一部分:

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="locations"> 
    <list> 
     <value>classpath:default.properties</value> 
    </list> 
    </property> 
</bean> 

<context:property-placeholder properties-ref="appProperties" /> 

我可以写下面的工作代码:

@Component 
public class MyComponent { 

    @Autowired 
    @Qualifier("appProperties") 
    private Properties appProperties; 

    @Value("${service.url}") 
    private String serviceUrl; 

    // remainder omitted 

} 

唯一问题是如果我从获得service.url的值我得到http://${server.host}/some/endpoint - 即价值未扩张。但是,如果我从serviceUrl获得service.url的值,则该值已扩展为:http://myhost.com/some/endpoint

有谁知道一个很好的方式来公开一个Properties实例作为一个其值已扩展的Spring bean吗?或者,如果任何人都可以将我指向一个Spring bean(必须是Spring 3.1),它将为我做扩展,我也会接受它! (有趣的是,如果您手动拉离Environment或属性值PropertySource你会发现,这些也未展开。)

感谢, 道穆埃尔。

+0

也许http://stackoverflow.com/a/7547942/180100 – 2012-10-25 06:34:19

+0

感谢您的链接。不幸的是,它并没有真正解决问题。我可以采用'@ Configuration'方法而不是XML,但是我需要做大量的代码来手动执行所有的扩展。 – Muel

+0

@Muel,你怎么看这个库我写道:http://owner.aeonbits.org它确实处理可变扩展,它是基于注释的。我不知道你是否可以和Spring一起使用它。 –

回答

0

我已经很晚了,但已经有足够多的时间了,我觉得它有必要做出快速反应。你看到的是Spring处理属性扩展的人为因素。当找到属性扩展需求时,只检查以前加载的源,而不检查当前正在加载的属性源。当文件加载时,没有以前的来源,所以$ {server.host}不会扩展。当您稍后通过@Value注释引用$ {server.url}时,会加载属性文件源并按照预期进行搜索。这就是@Value注解得到完全扩展的原因,但是从属性文件查询的结果却没有。