gpt4 book ai didi

java - 如何将属性值注入(inject)使用注解配置的Spring Bean中?

转载 作者:行者123 更新时间:2023-12-01 16:25:40 26 4
gpt4 key购买 nike

我有一堆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访问我感兴趣的属性?

最佳答案

您可以在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/62154627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com