Java Reference
In-Depth Information
Singleton Beans
In Chapter 2, β€œThe Basics of Java EE,” you saw the use of stateless and stateful session beans via
a simple annotation coni guration. Luckily, singletons offer a similar approach. Just by adding
the @Singleton annotation to a class, you can turn it into a singleton bean as shown in Listing 4‐7.
LISTING 4‐7: The implementations of the singleton pattern using @singleton
package com.devchronicles.singleton;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import java.util.logging.Logger;
@Singleton
public class CacheSingletonBean {
private Map<Integer, String> myCache;
@PostConstruct
public void start(){
Logger.getLogger("MyGlobalLogger").info("Started!");
myCache = new HashMap<Integer, String>();
}
public void addUser(Integer id, String name){
myCache.put(id, name);
}
public String getName(Integer id){
return myCache.get(id);
}
}
With the simple use of annotations, Java EE does not need a coni guration XML i le. You may
see a beans.xml i le in the project, but most of the time it remains empty. You only need it for
starting the Context and Dependency Injection (CDI) container. The @Singleton annotation
marks the class as a singleton EJB, and the container handles creation and usage of the single
instance.
If you execute this bean code on your server, you will not see logger output from the singleton
because the method annotated with @PostConstruct has not been invoked. Why is that?
Using Singletons at Startup
Singletons in Java EE are initialized lazily by default. This might suit most situations: allowing the
instance to be created only when it is needed and accessed for the i rst time. However, you may
want to create the instance at startup to allow access to the singleton without delay, especially if it's
 
Search WWH ::




Custom Search