我有一堆 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 中的属性之一注入(inject)到上面显示的 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
访问我感兴趣的属性?
最佳答案
您可以在 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;
这里是 blog post我写了这篇文章以获得更多信息。
关于java - 如何将属性值注入(inject)使用注释配置的 Spring Bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/317687/