【问题标题】:Inject Resolved Properties Object to Another Bean将解析的属性对象注入另一个 Bean
【发布时间】:2016-07-01 16:33:37
【问题描述】:

我想通过 XML 配置将 java.util.Properties 对象注入另一个 bean。我尝试了here 列出的解决方案,但没有成功,大概是因为在属性解析发生之前注入了 bean。有没有办法可以强制 java.util.Properties 对象在注入到我的班级之前解析?

以下是我所拥有的修剪/编辑版本。 PropertiesConsumingClass 确实收到了 a、b 和 c 属性文件的合并但未解析的属性。

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="properties" ref="allProperties" />
</bean>

<bean id="allProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="propertiesArray">
    <util:list>
      <util:properties location="classpath:a.properties" />
      <util:properties location="classpath:b.properties" />
      <util:properties location="classpath:c.properties" />
    </util:list>
  </property>
</bean>

<bean class="PropertiesConsumingClass">
  <constructor-arg index="0" ref="allProperties" />
</bean>

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您的示例不起作用,因为 Spring 调用的属性与 Java 调用的属性不同。基本上,Spring 属性位于&lt;property&gt; 标记中,这就是PropertyPlaceholderConfigurer 解决的问题。您还可以在 @Value 注释中使用属性占位符。无论哪种方式,您都有一个带有 ${} 占位符的字符串被解析,可能该字符串被转换为正确的类型,并注入到您的 bean 中。

    java.util.Properties 用于解析 Spring 属性中的占位符,但它们本身不被考虑解析。 a.b.c.properties 中的任何属性都将被替换为 Spring 属性占位符,但 PropertyPlaceholderConfigurer 不知道也不关心它从这些文件中获取的值是否包含 ${}

    现在,Spring Boot 确实在其配置文件中解析了占位符,但它有特殊的方法来实现这一点。它也是一个非常固执己见的库,它想要控制你的应用程序的生命周期并在幕后做很多神奇的事情,所以除了在项目的一开始就很难采用或放弃。

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      相关资源
      最近更新 更多