【问题标题】:Spring property initializationSpring属性初始化
【发布时间】:2017-01-27 18:00:19
【问题描述】:

我有一个带有以下属性占位符的 xml 可配置 Spring 上下文:

<context:property-placeholder
        properties-ref="dbProperties" location="classpath:logmessages.properties" order="2"/>

<context:property-placeholder location="classpath:application.properties" order="1"/>

DB属性配置bean如下:

<bean id="dbProperties"
    class="com.example.DatabasePropertiesLoader">
    <property name="path" value="${db.path}"/>
</bean>

因为它来自名称,所以这个 bean 从数据库加载一些属性,例如端点和其他服务的凭据。但是,要访问保存此属性的数据库,它还需要保存在 application.properties 中的凭据:

public class DatabasePropertiesLoader extends AbstractFactoryBean<Properties> {

   private String path;

   @Override
   protected Properties createInstance() throws Exception {
      // logic loading properties
   }

   @Override
   public Class<Properties> getObjectType() {
       return Properties.class;
   }

}

路径属性保存在 application.properties 文件中:

db.path=localhost:7777

如您所见,此 bean 需要注入“路径”属性才能创建。

但是无法做到,因为注入的值为空。我猜 Spring 只知道 application.properties 文件,而不知道它的内容。有没有办法解决这个问题?

【问题讨论】:

    标签: java xml spring spring-ioc


    【解决方案1】:

    需要告诉 spring 使用以下属性。

    @Value("${db.path}")
    private String path;
    

    【讨论】:

    • 我正在使用 XML 配置此字符串的作用完全相同:
    • 但是,您指的是其他属性文件? "properties-ref="dbProperties" location="classpath:logmessages.properties"
    • 我有 2 个属性占位符。请在回答明显错误之前阅读问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2013-12-16
    • 2013-01-06
    相关资源
    最近更新 更多