java 如何在 Spring 中连接相互依赖的 bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/425049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:20:38  来源:igfitidea点击:

How to wire Interdependent beans in Spring?

javaspringdependency-injection

提问by Sathish

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

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

<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"

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

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

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

采纳答案by neesh

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 只能在完全初始化后注入另一个 bean。在您的情况下,您有一个循环依赖项,可以防止任何一个 bean 被初始化,因为它们相互依赖。为了解决这个问题,您可以在其中一个 bean 中实现 BeanFactoryAware,并使用 beanFactory.getBean("beanName") 获取对另一个 bean 的引用。

回答by Henning

neesh is right, Spring doesn't do this out of the box.

neesh 是对的,Spring 不会开箱即用。

Interdependent beans hint at a design problem. The "clean" way to do this is to redesign your services in such a way that there are no such odd dependencies, of course provided that you have control over the implementations.

相互依赖的 bean 暗示了一个设计问题。做到这一点的“干净”方法是以没有这种奇怪依赖项的方式重新设计您的服务,当然前提是您可以控制实现。

回答by aledbf

you can extend the ApplicactionContext that are using and override the method createBeanFactory()

您可以扩展正在使用的 ApplicactionContext 并覆盖方法 createBeanFactory()

 protected DefaultListableBeanFactory createBeanFactory(){
    DefaultListableBeanFactory beanFactory = super.createBeanFactory();
    // By default this is false;
    beanFactory.setAllowRawInjectionDespiteWrapping( true );
    return beanFactory;
 }

This works, but be careful because this allows circular references.

这有效,但要小心,因为这允许循环引用。