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

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

问题描述

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

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>

但是Spring抛出一个异常说当前正在创建的FactoryBean从getObject返回了null"

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

为什么相互依赖的 bean 接线在这里不起作用?我应该在任何地方指定延迟的属性绑定吗?

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

推荐答案

不幸的是,Spring 中容器初始化的工作方式是,一个 bean 只有在完全初始化后才能注入另一个 bean.在您的情况下,您有一个循环依赖项,可以防止任何一个 bean 被初始化,因为它们相互依赖.为了解决这个问题,您可以在其中一个 bean 中实现 BeanFactoryAware,并使用 beanFactory.getBean("beanName") 获取对另一个 bean 的引用.

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天全站免登陆