Announcement Announcement Module
No announcement yet.
Cycle handling Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Cycle handling

    What is the best way to making two prototype beans aware of each other?

    Clearly cycles in a bean dependency graph won't work:
    	<bean id="a" class="RefBean1"	singleton="false">
    		<property name="ref"><ref bean="b"/></property>
    	<bean id="b" class="RefBean2"	singleton="false">
    		<property name="ref"><ref bean="a"/></property>
    causes Spring to loop until out of memory.

    Defining :

    <bean id="b" class="RefBean2"	singleton="false">
       <lookup-method name="lookupA"   bean="a"/>
    gives the same problem.

    Presumably this is because Spring tries to build a chain of instances A->B->A->B... .

    What I really want is A<=>B, i.e. A is supplied with a B instance and the B instance is made aware of the A instance.

    What is the best approach to handling this? Can this be done without making one of the beans a Singleton?

  • #2
    Could you write 2 simple FactoryBeans? (org.springframework.beans.factory.FactoryBean)

    Your FactoryBeans could take care of doing the A.set(B), and B.set(A) before returning a properly initialised A or B. They'd also need to continue to make sure that new RefBean1 and RefBean2 were used (just looking at the fact you're using prototypes).

    One FactoryBean would return an initialised RefBean1 and the other a RefBean2

    If your beans weren't prototypes, you could otherwise look at using a BeanFactoryPostProcessor to set the cyclic references after Spring had initialised.