4/21/2010

Example of EJB Interceptor class

EJB 3.x interceptor class can contain either EJB lifecycle callback methods (e.g., @PostConstruct, @PreDestroy, @PrePassivate, @PostActivate), or business interceptor methods (i.e., @AroundInvoke), or any combination of these methods. The following is a simple example of EJB interceptor class:

package test;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PrePassivate;
import javax.ejb.PostActivate;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class Interceptor1 {
@PostConstruct
protected void myPostConstruct(InvocationContext ctx) {

}

@PreDestroy
protected void myPreDestroy(InvocationContext ctx) {

}

@PostActivate
private void postActivate(InvocationContext ctx) {

}

@PrePassivate
private void prePassivate(InvocationContext ctx) {

}

@AroundInvoke
public Object businessIntercept(InvocationContext ctx)
throws Exception {
Object result = null;
try {
// PreInvoke: do something before handing control to the next in chain
result = ctx.proceed();
return result;
} finally {
// PostInvoke: do something (cleanup, etc) after the main processing is done
}
}
}
The interceptor class is attached to EJB bean class (or business method in EJB bean class) with @Interceptors annotation, or specified in ejb-jar.xml.