如何将属性值注入使用注释配置的 Spring Bean? [英] How can I inject a property value into a Spring Bean which was configured using annotations?
问题描述
我有一堆 Spring bean,它们是通过注释从类路径中提取的,例如
I have a bunch of Spring beans which are picked up from the classpath via annotations, e.g.
@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
// Implementation omitted
}
在 Spring XML 文件中,有一个 PropertyPlaceholderConfigurer 定义:
In the Spring XML file, there's a PropertyPlaceholderConfigurer defined:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/app.properties" />
</bean>
我想将 app.properites 中的一个属性注入到上面显示的 bean 中.我不能简单地做类似
I want to inject one of the properties from app.properites into the bean shown above. I can't simply do something like
<bean class="com.example.PersonDaoImpl">
<property name="maxResults" value="${results.max}"/>
</bean>
因为 PersonDaoImpl 在 Spring XML 文件中没有特征(它是通过注解从类路径中提取的).我有以下几点:
Because PersonDaoImpl does not feature in the Spring XML file (it is picked up from the classpath via annotations). I've got as far as the following:
@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
访问我感兴趣的属性?
But it's not clear to me how I access the property I'm interested in from ppc
?
推荐答案
您可以使用 EL 支持在 Spring 3 中执行此操作.示例:
You can do this in Spring 3 using EL support. Example:
@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }
@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }
systemProperties
是一个隐式对象,strategyBean
是一个 bean 名称.
systemProperties
is an implicit object and strategyBean
is a bean name.
再举一个例子,当您想从 Properties
对象中获取一个属性时,它会起作用.它还表明您可以将 @Value
应用于字段:
One more example, which works when you want to grab a property from a Properties
object. It also shows that you can apply @Value
to fields:
@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;
这是一个博文 我写了这篇文章以获得更多信息.
Here is a blog post I wrote about this for a little more info.
这篇关于如何将属性值注入使用注释配置的 Spring Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!