Tuesday, June 5, 2012

Solution for Spring circular reference

In Spring injection we may come acros circular reference exception.

Example for circular reference:
 <bean id="lookupService " class="com.AddressLookupServiceImpl">  
     <property name="xyzService" ref="xyzService" />  
   </bean>  
   <bean id="xyzService" class="com.XYZServiceImpl">  
     <property name="xyzService" ref="xyzService" />  
   </bean>    


  Here bean lookupService is referring to bean xyzService. Again bean xyzServiceis referring to lookupService. This is called circular reference.

To avoid circular reference issue, instead of having reference in child to parent we can just have the reference in parent bean alone as given below    

 <bean id="lookupService " class="com.AddressLookupServiceImpl">  
     <property name="xyzService" ref="xyzService" />  
   </bean>  
   <bean id="xyzService" class="com.XYZServiceImpl">  
   </bean>    

 Error creating bean with name 'XYZ': Bean with name 'XYZ' has been injected into other beans [XYZHelper, AHelper] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.

No comments:

Post a Comment