Search This Blog

Wednesday, February 24, 2010

Spring Circular Dependancies

Though it's not always normal to have Circular referencing service beans to be configured in spring, it's not a sin to do so. There are cases where each action is handled by a particular service and for that the call much travel between beans and bean methods to accomplish that. But in most cases this can be handled more elegantly by carefully re-organising the sequence of the calls.

When this is not possible, it requires to have circular dependency in spring beans.
But if you have Bean A and Bean B and if A has a reference to B and B has a reference to B, spring when initializing will throw error. There are few ways to get around this situation.

1. Implement ApplicationContextAware in one of the beans (let's say Bean A) and when the call to Bean B is first done from Bean A, look for Bean B in application context and initialize. This will be only required to be done for the first call, since after that in a singleton the reference of Bean B is catched. Therefore in the spring configuration only B will depend on A. A won't depend on B. But in real code A will depend on B and it will be referenced when it's first used.

2. Define A's dependency on B in the spring context, but while setting B on A set the reverse relation ship also.


in Bean A
setB(Bean b)
{
this.b = b;
b.setA(this);
}

in Bean B
set A(Bean a)
{
this.a = a;
}

in spring configuration only setB() is configured as setter injection. So B will be created first, but when setting B on A, A on B also is set.

No comments: