微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。