Simplest Possible EJB 3.1 Singleton - Injected Into Servlet 3.0, WAR Deployment 📎
@Singleton
public class MasterDataCache {
private Map cache;
@PostConstruct
public void initCache(){
this.cache = new HashMap();
}
public Object get(String key){
return this.cache.get(key);
}
public void store(String key,Object value){
this.cache.put(key, value);
}
}
How to compile:
You will need the the EJB 3.1 API in the classpath, or at least the @Singleton annotation.
How to deploy:
Just JAR the class and put the JAR into e.g: [glassfishv3]\glassfish\domains\domain1\autodeploy
How to use:
@WebServlet(name="SingletonTester", urlPatterns={"/SingletonTester"})
public class SingletonTester extends HttpServlet {
@EJB
MasterDataCache masterDataCache;
@Override
public void init(){
masterDataCache.store("startup", new Date());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
out.println("Startup time: " + masterDataCache.get("startup") );
} finally {
out.close();
}
}
}
And: there is no XML, strange configuration, libraries, additional frameworks or jars needed...
The whole WAR-project (Singleton) was checked in into: http://kenai.com/projects/javaee-patterns/. It was developed with Netbeans 6.8 and tested with Glassfish v3. The deployment took: INFO: Deployment of Singleton done is 272 ms.
See also: EJB 3 series and EJB 3.1 From Legacy To Secret Weapon
[See also "Real World Java EE Patterns - Rethinking Best Practices", ServiceStarter page 207 and especially Singleton 211]