Announcement Announcement Module
Collapse
No announcement yet.
Cycle handling Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • 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:
    Code:
    <beans>
    	<bean id="a" class="RefBean1"	singleton="false">
    		<property name="ref"><ref bean="b"/></property>
    	</bean>
    	<bean id="b" class="RefBean2"	singleton="false">
    		<property name="ref"><ref bean="a"/></property>
    	</bean>	
    </beans>
    causes Spring to loop until out of memory.

    Defining :

    Code:
    <bean id="b" class="RefBean2"	singleton="false">
       <lookup-method name="lookupA"   bean="a"/>
    </bean>
    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.

    Comment

    Working...
    X