Sunday, November 6, 2011

EJB 3.1 Singleton example

Simplest Possible EJB 3.1 Singleton - Injected Into Servlet 3.0, WAR Deployment
http://www.adam-bien.com/roller/abien/entry/simplest_possible_ejb_3_14

Java EE6 Tutorial : A Singleton Session Bean Example: counter
http://download.oracle.com/javaee/6/tutorial/doc/gipvi.html

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
*/
@javax.ejb.Singleton
public class MasterDataCache implements MasterDataCacheLocal {

private Map cache;

@PostConstruct
public void initCache() {
System.out.println("MasterDataCache.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("MasterDataCache.store " + 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
*/
@Stateless
public class TestService implements TestServiceRemote, TestServiceLocal {

@EJB
MasterDataCacheLocal masterDataCache;

@EJB
BackendBeanLocal service;

@Resource SessionContext sessionContext;

public void callService(){

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

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

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

}

}

No comments:

Post a Comment