#
Singleton Session Bean
This tutorial explains to you what a Singleton Session Bean in Java is.
A Singleton, is a class which is instantiated once per application and exist for the lifecycle of the application. The Singleton Session Beans (from EJB 3.1) are business objects having a global shared state within a JVM. The concept of "Singleton" is old, but for EJB, the concept was implemented differently.
NOTES:
The @Startup
annotation causes the bean to be instantiated by the container when the application starts.
The @PostConstruct
annotation before a method will call that method when the Singleton is initialized.
Here is class created as singleton (example):
package singleton;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@Startup
@Singleton
public class SingletonExample {
private int counter;
@PostConstruct
public void postConstruct() {
counter = 0;
System.out.println("postConstruct() method is called !");
}
public int getCounter() {
return counter;
}
public void setCounter(int newCounterValue) {
counter = newCounterValue;
}
}
When you deploy the EJB application the EJB container will initialize the Singleton and this could be seen in the logs: