我如何将一个属性值注入使用注解配置的 Spring Bean 中?

我有一堆Spring Bean,它们是通过注解从classpath中提取的,比如说

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
    // Implementation omitted
}

在Spring的XML文件中,有一个PropertyPlaceholderConfigurer定义。

<bean id="propertyConfigurer" 
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/app.properties" />
</bean>   

我想把app.property中的一个属性注入到上面的bean中。我不能简单地做如下事情

<bean class="com.example.PersonDaoImpl">
    <property name="maxResults" value="${results.max}"/>
</bean>

因为PersonDaoImpl并不在Spring的XML文件中出现(它是通过注解从classpath中获取的)。我已经做到了以下几点。

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

    @Resource(name = "propertyConfigurer")
    protected void setProperties(PropertyPlaceholderConfigurer ppc) {
    // Now how do I access results.max? 
    }
}

但我不清楚如何从`ppc'访问我感兴趣的属性?

另一个选择是添加如下所示的appProperties Bean。










                        ${results.max}


检索时,这个Bean可以被投到一个java.util.Properties中,它将包含一个名为results.max的属性,其值是从app.properties中读取。同样,这个Bean可以通过@Resource注解被依赖性地注入(作为java.util.Properties的一个实例)到任何类中。

就我个人而言,我更喜欢这个解决方案(与我提出的其他方案相比),因为你可以准确地限制哪些属性是由appProperties暴露的,而且不需要两次读取app.properties。

评论(1)

我需要有两个属性文件,一个用于生产,一个用于开发(不会被部署)的覆盖。

为了同时拥有这两个文件,一个可以自动连接的Properties Bean和一个PropertyConfigurer,你可以写。







            classpath:live.properties
            classpath:development.properties


并在PropertyConfigurer中引用Properties Bean。



评论(0)

一个可能的解决方案是声明第二个Bean,从同一个属性文件中读取。





这个名为'appProperties'的Bean属于java.util.Properties类型,可以使用上面的@Resource attruibute进行依赖注入。

评论(0)