Sunday, November 6, 2011

EJB 3.1 Singleton example

Simplest Possible EJB 3.1 Singleton - Injected Into Servlet 3.0, WAR Deployment

Java EE6 Tutorial : A Singleton Session Bean Example: counter

A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients.

Singleton bean - implements cache

package testservice;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

* Session Bean implementation class MasterDataCache
public class MasterDataCache implements MasterDataCacheLocal {

private Map cache;

public void initCache() {
this.cache = new HashMap();

public Object get(String key) {
System.out.println("MasterDataCache.get " + key);
return this.cache.get(key);

public void store(String key, Object value) {
System.out.println(" " + key);
this.cache.put(key, value);


TestService Session Bean
package testservice;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBContext;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

import testejb.BackendBeanLocal;

* Session Bean implementation class TestService
public class TestService implements TestServiceRemote, TestServiceLocal {

MasterDataCacheLocal masterDataCache;

BackendBeanLocal service;

@Resource SessionContext sessionContext;

public void callService(){

System.out.println("principal=" + sessionContext.getCallerPrincipal());

if(masterDataCache.get("dave") == null){
System.out.println("TestService:" );"dave","dave");
} else {
System.out.println("TestService: masterDataCache get" );

System.out.println("TestService: callService" );



No comments:

Post a Comment