Friday, March 5, 2010

Spring Dynamic Proxy - Avoid service layer pass-through methods

In a typical stack of view, service and dao layers, view always interacts with service layer and service layer talks to dao layer. Service layer is at a level higher than dao and its methods are much coarser in nature than dao methods. Typically a service method would manage a transaction that might spread across multiple dao operations. But many of the times in this layered approach, the service layer (business service) acts as a mere pass through to dao layer. We keep on adding newer and newer methods to service classes to satisfy more and more data needs of view layer. Since many of them are purely data needs, service layer straight passes them to dao layer. So the service and dao layer classes look something like this –

When you have to add new methods or change existing ones, you have to do the same thing at four different places.

Newer Design
The design pattern below addresses this issue to eliminate lot of boiler plate coding.


ServiceInterface – Design your service interface where it will perform some real business logic.

PassThruInterface – For lack of a better name, PassThroughInterface will contain service methods but are straight calls to dao. The approach is to separate the existing pass through methods in service layer into this PassThroughInterface.

PublishedInterface – This is the interface that would be visible to outside layer and consolidates both core ServiceInterface and PassThroughInterface. In OO terms, it extends both ServiceInterface and PassThroughInterface.

ServiceImpl – Implements only the real business methods where it does much more than calling dao methods.

DaoImpl – Implements both DaoInterface and PassThruInterface methods. From the coding perspective, there is no change as it would have done the same thing anyway in classic service -> dao approach.

ServiceRouter – This is the heart of the logic that routes method invocations with the help of dynamic proxy. As you can see, it is a specialized implementation of Spring’s FactoryBean interface and has references to both service and dao implementation classes. So when configured as a Spring bean, it returns a proxy instance of the PublishedInterface. ServiceInvocationHandler, an implementation of dynamic proxy MethodInvocation interface, inspects method calls on proxy interface and routes calls appropriately either to service implementation class or dao implementation class. A sample spring configuration would look like this –

Though the article here quotes service/dao interation, but the idea can used in service composition or to combine a core service and many decorating services around it.