Wednesday, October 25, 2006

Java annotations support in the web container

Servlet 2.5 (a part of Java EE 5) provides support for Java metadata annotations. You can use annotations for callback methods, security, injection of resources, EJB and web service reference, EntityManager, etc.

You can also package a persistence module (EJB3 JPA entities) as a part of a WAR module.

Injection of Resources

You can use the @Resource annotation to inject resource references such as Data Source e.g. you can inject a Data Source as follows:

@Resource(name="jdbc/OracleDS")
private DataSource dataSource;


CallBack Methods

You can use @PostConstruct and @PreDestroy annotations with any arbitrary method to behave like init() and destroy() methods respectively. For example you can have a method named openConnection that opens a connection as follows:

@PostConstruct
public void openConnection() {
try {
connection = dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}


Things to Remember


Note that annotations are supported only with managed classes such as servlet, filters, listeners, etc. You cannot use annotations with regular POJOs.

You have to make sure that you have set version=”2.5” in the web.xml for the web-app tag as follows: ...

...


If you have set that to a lower version or not set then container will not search for annotations and you will probably get a NullPointerException at run time when trying to use a field assuming it’s value to populated using injection.

OC4J 10.1.3.1 supports all Servlet 2.5 annotations that includes @EJB, @Resource, @Resources, @PostConstruct, @PreDestroy, @PersistenceUnit(s), @PersistenceContext(s), @WebServiceRef, @DeclaresRoles, @RunAs.

It also allows packaging of EJB 3/JPA entities in the web module.

Missing annotations ..!

I think one think that is missing is that there are annotations to specify a type of an object similar to @Stateless annotation in EJB 3.0.

For example, you CANNOT mark a POJO to be a servlet as follows:
@Servlet
public class MyServlet
{ …
}

I would like to see annotations such as @Servlet or @Filter in future version of Servlet specification.

More Info

You can find more about Servlet annotations in Servlet 2.5 spec or OC4J 10.1.3.1 documentation.


No comments: