Wednesday, November 17, 2010

How to Fix Java POJO Annotations


POJO and Annotation are a big part of the java world nowadays.  Spring, EJB, JPA, Servlet,  JSF and other technologies are using annotated POJOs. The traditional definition is that a POJO is an ordinary Java Object, which means it has no dependency on any framework or container.   

But take a look at the following example:
import javax.ejb.*;

@Stateless(name = "Test11", mappedName = "ejb.abc")
public class Test11Bean implements Test11{
      private static final long serialVersionUID = -128L;

  @EJB
  protected TestSb testsb;

  public Double getCost(String name, String expedite) {
      return 0.0;
}
….
}
As we can see, without ejb related jar file in the classpath, this code would not compile at all. If we want to use this in a weblogic container eventually, we may add “TransactionTimeoutSeconds” and other weblogic kodo related annotations.  In this case, we need to have vendor-specific jar files in order to compile this class. 

I think some changes can be done to make it a traditionally-defined POJO.  Here is what I would do:
I would change the “import” to “@import” (or maybe another new keyword.) This will serve as a hint during the compilation, deployment and run times. During different stages (compilation, deployment and run), depending on whether the related jar files are in the classpath, different actions can be taken to generate different artifacts.

What are the benefits of doing this?
1.       Code can be reused more often.  Sometimes I want to use a JPA POJO entity class as a pure simple bean (like a data transfer object) in another project,  it would be possible if it did not have dependency on some jars.
2.       Could make the testing easier.