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

发布于 2022-05-26 23:30:39

我有一堆 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
被浏览
14
1 个回答
  • 面试哥
    面试哥 2022-05-26
    为面试而生,有面试问题,就找面试哥。

    您可以使用 EL 支持在 Spring 3 中执行此操作。例子:

    @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万份考试真题开放下载啦

去下载看看