Using EJB Interceptors — Part 3

In the first two parts of this series of posts we looked at the around-invoke interceptors and method interceptors supported by EJB 3.1. In this post we will mention life-cycle interceptors.
With EJB 3.1 we can use annotations to inform the container to invoke a method at a bean’s certain life-cycle phases (@PostConstruct, @PrePassivate, @PostActivate, and @PreDestroy).
Life-cycle interceptors are similar to around-invoke interceptors which were covered in the previous blog post.
Here is a brief description of each life-cycle:

  • PostConstructThe annotated method is executed after dependency injection is done; and to perform any initialization. This method is invoked by the container before the bean is put into service. Only one method can be annotated with this annotation.
  • PrePassivate The annotated method is called before a stateful session bean is passivated.
  • PostActivate The annotated method is called a stateful session bean has been activated.
  • PreDestroy This annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container. Typically used by a bean to release the resources that it holds.

The output of the interceptor is shown below:

[#|PostConstruct @ TestLifeCycleInterceptor called|#]
[#|intercepting method call|#]
[#|Processing call calculate@com.sirius.test.SimpleSessionBean@1ffa739|#]
[#|=>1.0|#]
[#|=>2.0|#]
[#|Done with calculate@com.sirius.test.SimpleSessionBean@1ffa739|#]

EJB 3.1 lets developers to attach more than one interceptor to beans by using the @Interceptors annotation at the class level. @Interceptors annotation takes a comma-separated list of interceptors as a parameter. The order of which the interceptors are called is determined by the order in which they are specified in the @Interceptors annotation. To specify multiple interceptors:

@Stateless
@Interceptors(Interceptor_1.class, Interceptor_2.class)
public class TestEJB {
      @ExcludeClassInterceptors
      public Float testMethod(Float f) { ... }

In this example two interceptors are specified for the TestEJB and they will called in the order they are specified. By using the @ExcludeClassInterceptors annotation it is possible to exclude the testMethod from the definition of class level interceptors; hence the interceptors are not called for this method.

You can download the code for the application here. The application is tested on Glassfish v3.0.

  • Share/Bookmark

About this entry