Lifecycle Callbacks for Stateful Session Beans


Stateful session beans support callback events for the following events:

- construction
- destruction
- activation
- passivation

A method in the bean may be annotated to be executed when any of these events occur.


The PostContruct callback happens immediately after a bean is instantiated in the EJB container.
The bean may use dependency injection to get reference to other beans or resources, in that case the event happens after these injections are completed.
The method itself doesn't have to have a certain name. It can be called anything and is a good place to for example create a Logger instance for logging.
A method could look like this:


private Logger logger;

@PostConstruct
public void initialize() {
        logger = Logger.getLogger(ShoppingBeanImpl.class);
}


The PreDestroy event happens after a method has been completed which has the annotation @Remove (see below).
This would be a good place to for example place code to save the shopping cart to database.


@PreDestroy
public void exit() {

        // Code to save shopping cart here...

        System.out.println("Saved shopping cart!");
}

When a method is marked with the @Remove annotation,
it means that the stateful bean instance will be removed from the object pool of the container when the method has finished executing.

A method annotated with the @PrePassivate annotation will execute when for example the user has been idle for some time.
It could be a good method to store the state of the bean to a cache memory.

A method annotated with the @PostActivate annotation is executed when the user starts to use a passivated stateful session bean again.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: