如何在Spring中连接相互依赖的bean? [英] How to wire Interdependent beans in Spring?

查看:192
本文介绍了如何在Spring中连接相互依赖的bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要声明两个bean并使用Spring依赖注入来实例化?

 < bean id =sessionFactory类= SessionFactoryImpl > 
< property name =entityInterceptorref =entityInterceptor/>
< / bean>

< bean id =entityInterceptorclass =EntityInterceptorImpl>
< property name =sessionFactoryref =sessionFactory/>
< / bean>

但是,Spring抛出一个异常,称FactoryBean当前正在创建,从getObject返回null



为什么相互依赖的bean接线不在这里工作?我应该在哪里指定defferred属性绑定?

解决方案

不幸的是容器初始化在Spring中工作,一个bean只能被注入到另一个一旦它被完全初始化。在你的情况下,你有一个循环依赖,它阻止任何一个bean被初始化,因为它们依赖于彼此。要解决这个问题,您可以在其中一个bean中实现BeanFactoryAware,并使用beanFactory.getBean(beanName)获取对另一个bean的引用。


I want to declare two beans and instantiate them using Spring dependency injection?

<bean id="sessionFactory" class="SessionFactoryImpl">
 <property name="entityInterceptor" ref="entityInterceptor"/>
</bean>

<bean id="entityInterceptor" class="EntityInterceptorImpl">
 <property name="sessionFactory" ref="sessionFactory"/>
</bean>

But Spring throws an exception saying "FactoryBean which is currently in creation returned null from getObject"

Why is inter-dependent bean wiring not working here? Should i specify defferred property binding anywhere?

解决方案

Unfortunately the way container initialization works in Spring, a bean can only be injected in another bean once it is fully initialized. In your case you have a circular dependency that prevents either bean to be initialized because they depend on each other. To get around this you can implement BeanFactoryAware in one of the beans and obtain the reference to the other bean using beanFactory.getBean("beanName").

这篇关于如何在Spring中连接相互依赖的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆