Thursday, April 24, 2008

Liking Spring 2.5 (love annotations)

Ok, I think I feel comfortable in adopting or suggesting the Spring framework for JEE projects. And I am sure some people would say that they had reached that conclusion a long time ago. However, earlier I would tend to disagree on a couple of counts if someone suggested that Spring was the best thing to happen to Java and a better alternative to the existing JEE spec. The things I despised about Spring earlier were:
  • Too many libraries to include
  • Too much in an Xml configuration leading to some tricky runtime debugging errors
However, the Spring folks seem to have taken notice and have addressed these problems with Spring 2.5. So at my first opportunity, I decided to code with Spring 2.5 leveraging it mainly for its annotation facility. A really good resource I found for seeing the customization of Spring's annotation features is on InfoQ. However, I also extended a couple of the classes in Spring to be able to mimic resource manager injection capability (aka autowiring), similar to JPA persistent manager injection in JEE 5. The code looks something like this:

public class WiredBean
private Resource resource;

public boolean isInjected()
if ( resource!=null )
return true;
return false;

Spring allows renaming of annotations so that there is no dependency in your code on Spring classes. However to be able to inject (or autowire objects) based on your own annotation, requires some coding and essentially the following 2 things -
  1. Create your own class that extends InstantiationAwareBeanPostProcessorAdapter ( look at PersistenceAnnotationBeanPostProcessor for an example or email me for my example)
  2. Your Sping xml configuration needs really only 2 entries:
    1. An entry to register your own AnnotationBeanPostProcessor
    2. An entry to scan for your own autowiring annotation that allows one to override default behavior.
And you'll get code that looks like the above. Injecting your own manager objects into a JEE 5 application could be done using a Filter on the web side and Interceptors on the service/ejb side. If you are in an organization that wishes to avoid direct dependency on Spring all over the place in their JEE apps, custom annotations as I've mentioned allows for that separation.

No comments: