|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
