29.5.12

EJB Lifecycle Interceptor

Depending on the actually type of your Enterprise Java Bean you can have different lifecycle events e.g. PostConstruct or PreDestroy. It is also possible to create Interceptors for these callback methods. The following code shows an EJB with a intercepted callback method and the Interceptor implementation.


@Stateful
@Interceptors({MyInterceptor.class})
public class MemberRegistration{
   
    @PostConstruct
    public void init() {
           // do smg
    }
}

public class MyInterceptor implements Serializable{

    @PostConstruct
    public Object intercept(InvocationContext ctx) throws Exception{
         // do smg
        return ctx.proceed();
    }
}

The first thing to note  is that interceptors for lifecycle events can be just declared at class level; nothing happens if the annotation is added to the method. Furthermore, a general advice, do not forget to call the proceed method on the context object (unless intended). I saw several examples without it, which results in overwriting the intercepted method.

No comments:

Post a Comment