Lifecycle Callback methods of Stateless Session Bean
Below example demostractes Lifecycle Callback methods of Stateless Session BeanThe lifecycle callback methods can be defined in the bean class using annotations in EJB 3.0. It is called by EJB Container based on events.
The following annotations are used to define lifecycle callbacks in stateless session beans :
- @PostConstruct :@PostConstruct annotation method is called. It is used to initilise or allocate any resources.
- @PreDestroy : This method is called by the Container before destroying the Stateless Session Bean. It is used to release or close any resources used in the bean.
- The method must return void and does not take any arguments.
- The method should not throw any Checked Exception.
- The method can have any access specifiers – public, private, package-private and protected.
- The method can be final.
Below steps are to create Stateless session bean :
- Create Enterprise Application Project StatelessCallbackMethods.ear.
- Create Stateless Session Bean with Local interface in EJB project.
- Create index.jsp in Web project.
- Create Servlet in Web project.
- Run the Application.
Step 1: Create Enterprise Application Project StatelessCallbackMethods.ear with EJB (StatelessCallbackMethodsEJB)and Web (StatelessCallbackMethodsWeb) Module :
[ Click here if you are not familiear how to create Enterprise Application Project ]
Specify the Enterprise Application Project name StatelessCallbackMethods and click Next.
Below screen is used to create EJB and Web module in Enterprise Application Project. Click New Module
Step 2: Create Stateless Session Bean class StatelessCallbackSession and local interface StatelessCallbackSessionLocal :
This step will create two java file. One will be local interface StatelessCallbackSessionLocal.java and other will be bean class StatelessCallbackSession.java.
Edit both class java file as below :
Step 3: Add EJB Project to Web project
Right Click on Web Project - > Properties - > Java Build Path -> Click Projects -> Add -> Select StatelessCallbackMethodsEJB.
Step 4: Create index.jsp in Web project
Step 5: Create Servlet Servlet1.java in Web project
Step 6: Verify the directory structure as below -
Step 7: Run the Application
Right click on Web Project -> Run As -> Run on Server
Input any message and click Call EJB
You will get below output -
After running the application, undeploy project from server then container will call @PreDestroy method.
|Previous||Download Source Code||Next|