Spring PropertiesFactoryBean自动公开PropertyPlaceholderConfigurer的属性

时间:2011-12-31 13:54:36

标签: spring

理想情况下,我想从代码中执行此操作:

@Value("#{aPropertiesFactoryBean.aProperty}")
private String aProperty;

基于spring配置,我在其中设置PropertyPlaceholderConfigurer和PropertiesFactoryBean,并将配置器bean作为ref传递给bean,配置器生成的所有内容都作为工厂bean的属性公开。

有一个黑客可以从Configurer重新定义每个属性,如:

<bean id="aPropertiesFactoryBean" 
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="singleton" value="true" />
    <property name="properties">
      <props>
        <prop key="aProperty">${aProperty}</prop>
      </props>
    </property>
</bean>

然后每次向Configurer添加属性时,都必须使用FactoryBean重新公开它。简而言之,我想要配置器的所有管理功能,并且还能够从spring xml文件和@Value注释中引用同一批属性。

所以这两个问题:

  1. 开箱即用的是这样的吗?
  2. 看起来覆盖PropertiesFactoryBean并给它一个PlaceholderConfigurer属性会很简单,但实际访问属性的代码必须通过反射和挖掘Spring的内部PropertiesLoaderSupport类来解决问题。是否有一种不太常见的方法呢?
  3. 注意,我不是在寻找可以让我快速上路的东西,现在上面有关于PropertiesFactoryBean的黑客攻击就足够了。我希望找到或制作一个可重复使用的组件,我可以用它来轻松管理未来项目的可注射属性。

2 个答案:

答案 0 :(得分:3)

我只是在考虑这个问题。这个配置正是我想要的,能够在xml配置中定义属性,可以从属性文件覆盖,并且可以作为占位符属性和可注入值使用。

<beans 
  xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans        
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <!-- 
   One-stop shopping for properties here. 
   Available as injected values and elsewhere in the spring config. 
  -->
  <bean id="injectableProperties" 
            class="org.springframework.beans.factory.config.PropertiesFactoryBean">         
          <property name="singleton" value="true" />
          <property name="ignoreResourceNotFound" value="true" />
          <property name="properties">
            <props>
              <prop key="prop1">value1</prop>
              <prop key="prop2">value2</prop>               
            </props>
          </property>
          <!-- Allow foo.conf to override default properties -->
          <property name="location" value="file:/etc/foo/foo.conf" />
  </bean>

  <!-- Expose the properties so other parts of the spring config can use them -->
  <bean id="propertyPlaceholderConfigurer" 
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="ignoreUnresolvablePlaceholders" value="false" />
    <property name="properties" ref="injectableProperties"/>
  </bean>
</beans>

答案 1 :(得分:0)

也许我误解了这种情况,但您可以通过使用语法来注入属性而无需定义PropertiesFactoryBean

@Value("${my.property}") String myProperty;
相关问题