Creating a Singleton Session Bean

Business Interface

Create the bean interface and mark it either as @Remote, @Local or @WebService.

Remote Interface

import javax.ejb.Remote;

@Remote
public interface ProductRegistry {
	double getPrice(int id);
	void setPrice(int id, double price);
}

Local Interface

import javax.ejb.Local;

@Local
public interface ProductRegistry {
	double getPrice(int id);
	void setPrice(int id, double price);
}

Web service interface

import javax.jws.WebService;

@WebService
public interface ProductRegistry {
	double getPrice(int id);
	void setPrice(int id, double price);
}

Bean implementation class

Create a class which implements the business interface. Mark this class as singleton session bean using @Singleton annotation before the class signature.

package com.ibytecode.businesslogic;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import com.ibytecode.business.ProductRegistry;

@Singleton
public class ProductRegistryBean implements ProductRegistry {
	Map<Integer, Double> pdtRegistry;
	
	@PostConstruct
	void initialize()
	{
		pdtRegistry = new HashMap<Integer, Double>();
		pdtRegistry.put(100, 5000.00);
		pdtRegistry.put(101, 6000.00);
		pdtRegistry.put(102, 7000.00);
		pdtRegistry.put(103, 8000.00);
		pdtRegistry.put(104, 9000.00);
	}
	
	public double getPrice(int id) {
		return pdtRegistry.get(id);
	}

	public void setPrice(int id, double price) {
		pdtRegistry.put(id, price);
	}

	@PreDestroy
	void cleanup()
	{
		pdtRegistry = null;
	}
}

Leave a Comment