Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wire Interdependent beans in 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>

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?

like image 427
Sathish Avatar asked Jan 08 '09 17:01

Sathish


People also ask

How do you wire beans in Spring?

There are two ways to wire beans in the Spring framework: one, you wire the beans manually by declaring the beans, using the Dependency Injection (DI) and so on and two, let the Spring container wire the required beans. The latter process is known as auto wiring.

What is @lazy annotation in Spring?

@Lazy annotation indicates whether a bean is to be lazily initialized. It can be used on @Component and @Bean definitions. A @Lazy bean is not initialized until referenced by another bean or explicitly retrieved from BeanFactory . Beans that are not annotated with @Lazy are initialized eagerly.

Which configuration is used for dependency injection?

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods.


2 Answers

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

like image 117
neesh Avatar answered Oct 20 '22 05:10

neesh


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.

like image 20
Henning Avatar answered Oct 20 '22 07:10

Henning