小编典典

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

spring

我有一堆Spring bean,它们是通过注释从类路径中拾取的,例如

@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.properites的属性之一注入到上面显示的bean中。我不能简单地做这样的事情

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

因为PersonDaoImpl在Spring XML文件中没有功能(它是通过注释从类路径中拾取的)。我有以下内容:

@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


阅读 664

收藏
2020-04-11

共1个答案

小编典典

你可以在Spring 3中使用EL支持进行此操作。例:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties是一个隐式对象,并且strategyBean是Bean名称。

还有一个示例,当你想从Properties对象中获取属性时,该示例将起作用。它还显示你可以应用于@Value字段:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;
2020-04-11