gpt4 book ai didi

java - AutowireCapableBeanFactory : How to initialize primitive properties

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:15 24 4
gpt4 key购买 nike

我有一些以编程方式创建的 bean,我正在通过 AutowireCapableBeanFactory.autowireBean() 初始化它们,如下所示:

spring.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:annotation-config/>

<bean id="MyService" class="...">
<property name="someProp" value="primitiveValue"/>
</bean>

<bean id="MyBean" class="...">
<property name="someString" value="primitiveValue"/>
</bean>
</beans>

MyBean.java

public class MyBean implements InitializingBean {

@Autowired MyService myService;

private String someString;
public void setSomeString (String someString) {
this.someString = someString;
}
public void afterPropertiesSet () {}
}

来电者:

MyBean bean = new MyBean(arg1, arg2, arg3);
autowireCapableBeanFactory.autowireBean(bean);

这会按预期正确 Autowiring bean.myService。但是,它不会填充像 bean.someString 这样的原始属性。

查看文档和 this answer ,我认为这样的事情会起作用:

MyBean bean = new MyBean(arg1, arg2, arg3);
autowireCapableBeanFactory.autowireBean(bean);
autowireCapableBeanFactory.initializeBean(bean, "name");

但是可惜,someString 仍然是null。我找到了很多引用资料,说明什么不能用于初始化类属性,但没有任何内容表明什么可以工作。

有什么想法吗?

最佳答案

发现我可以使用AutowireCapableBeanFactory.applyBeanPropertyValues()来完成我想要的。注入(inject) @Autowired beans 和原始属性的代码如下所示:

@Autowired AutowireCapableBeanFactory beanFactory;

...

MyBean bean = new MyBean();
beanFactory.autowireBean(bean);
beanFactory.applyBeanPropertyValues(bean, bean.getClass().getSimpleName());

关于java - AutowireCapableBeanFactory : How to initialize primitive properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47824113/

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