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.

Thursday, February 11, 2010

Hibernate / Dao/ Object Graphs

Hibernate is an excellent ORM package. It eliminates all SQL/ data access code from a java project. But it introduces a problem if not care is taken in designing.

In one of my projects, we modeled a very deep tree of objects and if required with one single query we could load the entire database. This is dangerous and has big performance hits.

The approach for the next project would be.
1. Use Hibernate and keep data integrity with constrains.
2. Have a DAO to control every 3 or 4 model objects. each dao will manage a coarse grained object.
3. Hibernate cannot fetch a deep tree object because the objects will be disconnected at hibernate level.
4. for querying 'private fields' will be used. in the hibernate hbm.xml files the relationships for queries will be done using 'field' accessor. That means still querying is possible, but no deep fetching or lazy initializing exceptions which can happen due to getters in closed session.