Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create Singleton Session Bean in Java

In this article, we will see how to create a singleton session bean that performs similar functionality to that of the StatefulHelloWorldBean.

Singleton session beans represent an implementation of the singleton pattern. Singleton session beans can be used to provide shared access and concurrent access across clients. A singleton session bean is instantiated once per application and exists for the life cycle of the application. Sometime the container can be distributed over many virtual machines. In that case each application will have one bean instance for its own use. This is because the JVM is different.

Creating the Singleton

Creating a singleton session bean is similar to creating other session beans. The javax.ejb.Singleton(@Singleton) annotation is used to specify that the enterprise bean implementation class is a singleton session bean. Like stateless session beans, singleton session beans can contain instance variables as well as implement web service endpoints. Singleton beans support the following implementation strategies:

  • Remote and local client access mode
  • Business interface view
  • No-interface view
  • Web service endpoint Code 5-1 illustrates a minimal implementation of a no-interface singleton session bean. Code 5-1Mimimal
  • Implementation of a No-interface Singleton Bean
@LocalBean
@Singleton
public class SingletonBean {
//...
}

Singleton session beans have a life cycle that mirrors the common session bean life cycle transitions. In fact, the life cycle of a singleton bean is very similar to that of a stateless bean. As a singleton session bean transitions through the life cycle, there are a few important details that are worth noting, specifically in terms of the “instantiation,” “Ready,” and “PreDestroy” phases.

Remember, the StatefulHelloWorldBeanrecorded each sayHellomethod call as aGreetingRequest stored in a list. However, the StatefulHelloWorldBeanonly recorded requests for a specific client.

In this exercise, we will create a session bean that records sayHello method calls for all clients. This exercise contains the following sections:

  • “Task 1 -Create the Singleton Bean”
  • “Task 2 -Add Tracking to Singleton”
  • “Task 3 -Test the SingletonHelloWorldBean”
  • “Task 4 -Run the Application”

Task 1 - Create the Singleton Bean

In this task, we will create a singleton EJB using the NetBeans IDE. Complete the following steps:

  • Right-click on the EJB31-ejbmodule in the Projects tab and select: New > Session Bean
  • Fill in the EJB information in the wizard to create a stateless session bean.
  • Specify SingletonHelloWorldBeanas the EJB Name.
  • Define the package as helloworld.beans.
  • Select Singleton for the Session Type.
  • Select the check box labeled Create Remote Interface
  • Click the Finish button.

Review the created SingletonHelloWorldBean.Make sure to note the @Singletonannotation.

Task 2 - Add Tracking to Singleton

In this task, we will modify the SingletonHelloWorldBeanto implement functionality similar to that found in the StatefulHelloWorldBean. In particular, we will create sayHelloand sayGoodByemethods. Complete the following steps:

  • Add the following import statements: import javax.ejb.EJB; import java.util.*; import helloworld.vo.*; import javax.annotation.PreDestroy;
  • Declare an instance variable for the no-interface stateless bean. @EJB private TimeBasedHelloWorldBean timeBasedHelloWorldBean;
  • Declare an instance variable of type List. private List<GreetingRequest> greetingRequests;
  • Add a constructor to initialize the greetingRequest. public SingletonHelloWorldBean(){ greetingRequests = new ArrayList<GreetingRequest>(); } Implement the sayHellomethod in the SingletonHelloWorldBean.
  • Right-click in the editor and choose Insert Code > Add Business Method

Specify the method information as follows:

  • Name: sayHello
  • Return Type: GreetingRequest
  • Ensure that the Remote radio button is selected
  • Click the OK button.

Modify the sayHellomethod as follows: public GreetingRequest sayHello() { String greeting = timeBasedHelloWorldBean.say Hello(); GreetingRequest request = new GreetingRequest (greeting); greetingRequests.add (request); return request; } Open SingletonHelloWorldBeanRemote.jav aand add the following import statement import helloworld.vo.GreetingRequest; Implement the auditRequests method in the SingletonHelloWorldBean a. Right-click in the editor and choose Insert Code > Add Business Method b.Specify the method information as follows:

  • Name: auditRequests
  • Return Type: GreetingRequest []
  • Ensure the Remote radio button is selected.
  • Click the OK button.
  • Review the modifications made to the remote interface.

Listing 1: Modify the auditRequestmethod to return a current snapshot of the list elements.

public GreetingRequest[]
auditRequests() { return greetingRequests.toArray (new GreetingRequest[] {}); } Implement a @PreDestroylife cycle callback named destroy: a.Iterate through the list of greeting request. b.Print each request in the list. c.Nullify the list. @PreDestroy private void destroy() { System.out.println ("helloworld.beans.Singleto nHelloWorldBean: @PreDestroy"); for(GreetingRequest gr : greetingRequests) { System.out.println(gr); } greetingRequests = null; }

Task 3 - Test the SingletonHelloWorldBean

In this task, we will do an iterative test of the code written so far. While this task does not follow a true test-driven development process, it allows we to perform a sanity check before instrumenting the session bean with life cycle callbacks. To perform this task, we will create a stand-alone application that performs a unit test. Complete the following steps:

Right-click StandAloneApp project and select New > Other > Java Main Class

Fill in the wizard to create the Java class:

  • Specify SingletonHelloWorldBeanTest as the Class Name.
  • Define the package as standaloneapp.
  • Click the Finish button.

Open the SingletonHelloWorldBeanTest.java class in the source code editor window.

Include the following import statement: import helloworld.vo.GreetingRequest; import helloworld.beans.SingletonHelloWo rldBeanRemote; import javax.naming.*;

Listing 2: Declare a static instance variable named

helloWorldBean. private static SingletonHelloWorldBeanRemote helloWorldBean; 

Open standaloneapp.Main.java.

  • Copy the entire main method.
  • Replace the SingletonHelloWorldBeanTest.main method with the copied method.
  • Close standaloneapp.Main.java.

Modify the SingletonHelloWorldBeanTest.main.

Modify the following variables:

  • jndiPath-Use the following path: String jndiPath = "java:global/EJB31/ EJB31-ejb/ SingletonHelloWorldBe an";
  • helloWorldBean-Fix the cast as part of the JNDI lookup. helloWorldBean = (SingletonHelloWorldB eanRemote) ctx.lookup (jndiPath);
  • greeting-Fix the type to be GreetingRequest. GreetingRequest greeting = helloWorldBean.sayHel lo();

Modify the System.outcall to reflect the correct class name

Audit the singleton bean by calling the auditRequestsmethod GreetingRequest[] audit = helloWorldBean.auditRequest s(); System.out.println ("SingletonHelloWorldBeanTe st.main: number of sayHello requests made on Singleton: " + audit.length);

Note: Before running the application, make sure appserv-rt.jar is included as one of the libraries for web project.

Task 4 - Run the Application

To execute the application in NetBeans, complete the following steps:

  • Verify that the EJB31 application is deployed and running in GlassFish.
  • In the Editor tab, right-click on the SingletonHelloWorldBeanTest.
  • Select Run from the pop-up menu
  • Examine the output in the StandAloneApp (run) tab.

Listing 3: We should observe a message similar to the following in the tab:

SingletonHelloWorldBeanTest.main: looking up bean at: java:global/EJB31/EJB31-ejb/ SingletonHelloWorldBean
SingletonHelloWorldBeanTest.main: found SingletonHelloWorldBean:
helloworld.beans._SingletonHelloW orldBeanRemote_Wrapper@5aeeffc8 SingletonHelloWorldBeanTest.main: calling sayHello SingletonHelloWorldBeanTest.main: bean said: helloworld.vo.GreetingRequest [requestTime=11/6/09 10:23 AM,greeting=Good Morning] SingletonHelloWorldBeanTest.main: number of sayHello requests made on Singleton: 1

Note To experience the Singleton aspect of the bean, try running the SingletonHelloWorldBeanTest multiple times. We will see the number of requests increase.

Managing Singleton Dependencies

The previous exercise and previous labs referenced the TimeBasedHelloWorldBean to derive a time-sensitive greeting. Even though the TimeBasedHelloWorldBean is stateless, under certain circumstances and load, more instances of the bean may exist in memory than is necessary.

Conclusion

In this article, we modified the TimeBasedHelloWorldBeanto function as a @Singleton. Additionally, we managed the singleton initialization dependency between the SingletonHelloWorldBeanand the TimeBasedHelloWorldBean.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login