Singleton EJB tutorial
Page 1 of 2
One of the most interesting news of Java EE 6 is the Singleton annotation which can be used to mark your EJB as Singleton services.
As the name implies a javax.ejb.Singleton is a session bean with a guarantee that there is at most one instance in the application. Until now if you wanted to expose a Service as Singleton you had to use either Service POJOS (See an article here JBoss MBeans POJOs ) or tweak the EJB pool maximum size.
All of these approach worked, however they were not portable because they used JBoss annotations/configuration to do the trick.
Now with the latest release of JBoss 6 M3 you can use a Java EE 6 full compliant solution. Making an EJB as Singleton is pretty easy: just add the java.ejb.Singleton annotation and that's all.
Here's an example:
In this example, the EJB exposes a trivial add(int i) method which increments a counter. Since there will be just one instance of SingletonBean, the total variable can be used across client calls.
Notice also the @Startup annotation which is not mandatory but can be used to signal to the container to invoke the @PostConstruct method just after the Bean has been created. So, if you need a proper Bean initialization, just add a @Startup annotation at Class level and a @PostConstruct at method level.
Testing the EJB is pretty simple, here's a remote client example:
All of these approach worked, however they were not portable because they used JBoss annotations/configuration to do the trick.
Now with the latest release of JBoss 6 M3 you can use a Java EE 6 full compliant solution. Making an EJB as Singleton is pretty easy: just add the java.ejb.Singleton annotation and that's all.
Here's an example:
In this example, the EJB exposes a trivial add(int i) method which increments a counter. Since there will be just one instance of SingletonBean, the total variable can be used across client calls.
Notice also the @Startup annotation which is not mandatory but can be used to signal to the container to invoke the @PostConstruct method just after the Bean has been created. So, if you need a proper Bean initialization, just add a @Startup annotation at Class level and a @PostConstruct at method level.
Testing the EJB is pretty simple, here's a remote client example:

