Developing singleton EJBs
As the name implies, javax.ejb.Singleton is a session bean that guarantees that
there is at most one instance in the application.
Besides this, singleton EJBs fill a well-known gap in EJB applications, that is, the ability to
have an EJB notified when the application starts and also when the application stops. So,
you can do all sorts of things with an EJB that you previously (before EJB 3.1) could only
do with a load-on-startup servlet. EJB also gives you a place to hold data that pertains to
the entire application and all the users using it, without the need for static class fields.
In order to turn your EJB into a singleton, all that is needed is to apply the
@javax.ejb.Singleton annotation on top of it.
A singleton bean is similar to a stateful bean, in that, state information is maintained across
method invocations. However, there is just one singleton bean for each server JVM, and it
is shared by all of the EJBs and clients of an application. This type of bean provides a con-
venient means to maintain the overall state of an application. However, if the application is
distributed on multiple machines (and therefore multiple JVMs), the singleton is unique on
every one of them. Any application state must be synchronized between the nodes.
Another annotation that is worth learning is @javax.ejb.Startup , which causes the
bean to be instantiated by the container when the application starts. This invokes the meth-
od decorated with the @javax.annotation.PostConstruct annotation if you have
defined one in your EJB.
We now have enough information to understand our first EJB example. There is more than
one alternative to create a Java Enterprise project. In the earlier chapter, we illustrated how
to start from a project based on Eclipse Java EE (a dynamic web project), binding it later to
a WildFly runtime installation. This is obviously the simplest choice, and you can easily
run the examples contained in this topic using this pattern; however, when it comes to en-
terprise solutions, it's no surprise that almost every project now uses some kind of build
automation tool. For this topic, we will propose Apache Maven, as it is one of the most
popular choices, but not the only one. Gradle is a similar project that uses the Groovy lan-
guage to describe project structure, dependencies, and build workflow.
Search WWH ::