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

发布于 2021-02-02 18:16:50

我有一堆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

关注者
0
被浏览
290
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以在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;
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看