Lifecycle Callbacks for Stateless Session Beans


The J2EE server (like Glassfish or Oracle Weblogic) manages the life cycle of a stateless session bean unlike regular Java classes. The server decides when to create and remove bean instances, so the application never knows how many instances of a session bean class that is created, nor does it know when they are created or destroyed.
Since the server itself needs to initialize services for the bean before the business logic is invoked, and the bean itself most likely will need to make some initializations of itself,
the constructor is not a good place for that bean initialization code.
To allow both the server and the enterprise bean to make their initializations, EJBs support something called "lifecycle callback methods" that are annotated by the programmer and invoked by the server at various points in th bean's life cycle.

For stateless session beans there are two lifecycle callbacks:


@PostConstruct

@PreDestroy


The server will invoke the method that is annotated with the @PostConstruct annotation as soon as the server is finished with its initialization tasks,
and the server will also invoke the method annotated with the @PreDestroy annotation immediately before the bean instance is released for garbage collection.

A good use of the @PostConstruct annotation could be to get hold of a Logger instance.


package com.javadb.examples;

import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;

/**
 *
 * @author javadb.com
 */

@Stateless
public class PasswordBeanImpl implements PasswordBeanLocal {

    private Logger logger;
    
    @PostConstruct
    public void initBean() {
        logger = Logger.getLogger(PasswordBeanImpl.class.getName());
    }

    public String getGeneratedPassword() {

        String generatedPassword = null;

        //Code to generate password here

        return generatedPassword;
    }
}

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: