How to wire Interdependent beans in Spring?

前端 未结 4 2100
既然无缘
既然无缘 2020-12-15 06:40

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


 

        
相关标签:
4条回答
  • 2020-12-15 07:14

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

    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.

    0 讨论(0)
  • 2020-12-15 07:17

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

    0 讨论(0)
  • 2020-12-15 07:26

    you can extend the ApplicactionContext that are using and override the method 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.

    0 讨论(0)
  • 2020-12-15 07:32

    You can implement a BeanPostProcessor that sets the dependency.

    Or...

    See Costin's reply here:

    http://forum.springframework.org/showthread.php?t=19569&highlight=circular+dependencies

    See Andreas' reply here:

    http://forum.springframework.org/showthread.php?t=29572&highlight=circular+dependencies

    0 讨论(0)
提交回复
热议问题