Home > EJB3, java | > EJB3 tutorial part 03: session bean’s lifecycle callbacks

EJB3 tutorial part 03: session bean’s lifecycle callbacks

November 17th, 2009

In previous posts we've learned how to create Session Beans (both Statless and Stateful). In this post I would like to show how to use lifecycle callbacks.

What are lifecycle callbacks?

Lifecycle callbacks are calls to specific methods that occur when certain lifecycle events happed, for example creation of the instance.

Why it's important to me?

It's important from the developers perspective as you can implement those callback methods and do some useful things in them. We mentioned that usually a container will maintain a pool of session bean instances. So once the instance is created it can be reused over and over again. The biggest gain from instance pooling is that we don't need to reinitialize the instance every time the business method is called. So with the lifecycle callbacks you can for example initialize some resource after the instance is created and remove it when the instance is removed. Between those two callbacks you can reuse the initialized resource.

Simple example how to create lifecycle callbacks. On the Statless Bean just add methods with annotations:

 
@PostConstruct
public void postConstruct() {
  System.out.println("Create");
}
 
@PreDestroy
public void preDestroy() {
  System.out.println("Destroy");
}
 

@PostConstruct annotates method that is called right after the instance is created. @PreDestroy annotates method that is called just before the instance is destroyed. Stateful beans have also two additional annotations: @PrePassivate and @PostActivate. Passivation and activation happen when container decides to put particular instance aside. It may happen when a client that is using an instance does not use it for a longer time and container needs new instances.

One important thing to remember is that @PreDestroy method is not guaranteed to run. If there is a crach of a container or a machine, or just power off, to @PreDestroy may not run. On the other hand is your business method is running you are guaranteed that @PostConstruct method has been called. You must keep that in ming when allocating any resources in @PostConstruct and freeing them in @PreDestroy.

For more details on lifecycle callbacks please refer to JSR-220. The specification describes how these lifecycle callback fit into the overall lifecycle and provide information on transactions and security for the callback methods.

EJB3, java |

  1. No comments yet.
  1. No trackbacks yet.