Reputation: 1849
Can anyone explain the full process of implementing a Singleton in a Java EE 6 app? I'm assuming that I shouldn't be creating a singleton in the typical way of declaring a static variable and should be using the @Singleton
annotation? Do I have to do it this way?
Is it just a case of declaring it @Singleton
and that's it? Do I have to do anymore to the class?
What do I then need to do to access the singleton in my other classes?
Upvotes: 6
Views: 11988
Reputation: 1108557
Is it just a case of declaring it @Singleton and that's it?
Yes! That's it! Just design the class like any other Javabean.
Do however note that this is indeed not the same as GoF's Singleton design pattern. Instead, it's exactly the "just create one" pattern. Perhaps that's the source of your confusion. Admittedly, the annotation name is somewhat poorly chosen, in JSF and CDI the name @ApplicationScoped
is been used.
What do I then need to do to access the singleton in my other classes?
Just the same way as every other EJB, by injecting it as @EJB
:
@EJB
private YourEJB yourEJB;
Upvotes: 9
Reputation: 68715
The javax.ejb.Singleton
annotation is used to specify that the enterprise bean implementation class is a singleton session bean.
This information is to tell the ejb container, not to create multiple instance of this bean and only create a singleton instance. Otherwise it is just a normal bean class. Read more here:
http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html
You don't have to create a static variable, and do all the related stuff to make it singleton. Just write a normal bean as mentioned here and container will take care of instantiating only object of it:
@Startup
@Singleton
public class StatusBean {
private String status;
@PostConstruct
void init {
status = "Ready";
}
...
}
Upvotes: 3