views:

1109

answers:

4

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?

+2  A: 

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

neesh
I do not have this problem when i tried out with simple classes like BeanA and BeanB.
Sathish
+2  A: 

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.

Henning
+1 for redesign - you shouldn't need such interdependence.
matt b
I don't think his design is at question here (we know nothing of the problem and the solution); The question here is how can one deal with circular dependencies among objects managed by the Spring container.
neesh
And the answer, IMHO, is not to - unless you don't have a choice because the implementation isn't yours, in which case the solutions provided here will do the trick. The two services are either just one service, or there is a third, higher-level service waiting to be discovered.
Henning
+1  A: 

You can implement a BeanPostProcessor that sets the dependency.

Or...

See Costin's reply here:

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

See Andreas' reply here:

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

opyate
A: 

Hi, 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.

aledbf