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

JNDI and EJB Lite: Whats New in EJB 3.2

In this article you can see some of the new features of the Enterprise JavaBeans 3.2 release (EJB 3.2), such as JNDI and EJB Lite.


A session bean can be packaged into a ejb-jar file or within a web application module (.war). A deployment descriptor optional for EJBs called "ejb-jar.xml" which provides additional information about the deployment can be packaged in a "ejb-jar" or ".war".

The file "ejbjar.xml" can be packaged in "WEB-INF/ejb-jar.xml" or "META-INF/ejb-jar.xml" within a JAR file "WEB-INF/lib" but not in both.

A local bean or without interface that is packaged in a file ".war" is accessible only to other components within the same file ".war". However, a bean labeled @Remote is remotely accessible regardless of their packaging.

The file "ejb-jar" can be deployed alone or packaged within a file ".ear". The beans packed in this "ejb-jar" can be accessed remotely.

We can access this EJB using a global JNDI name with the following syntax:


Which applies only if the session bean is packed with a file ".ear". is the module name in which the session bean is packaged. It is the ejb-name of the enterprise bean.

If the bean exposes only a client interface (or alternatively have only one interface without display), the bean is also exposed to an additional JNDI name using the following syntax:


The bean with no session state is also available through the namespaces "java: app" and "java: module".

If the AccountSessionBean is packaged in a banco.war file, then the JNDI entries are exposed as follows:



A bean can use programmatic transaction directly in the bean code, which is called "managed transaction bean". Alternatively, we can also use a declarative transaction, that way transactions are managed automatically by the Accountiner, which is called "transaction managed by the Accountiner."

By default, transactions are managed by a bean Accountiner. The @TransactionManagement annotation is used to declare the session bean or the Message-Driven Bean uses a managed transaction bean or Accountiner. The value for this annotation can be ACCOUNTINER, which is used by default, or bean.

A managed transaction bean requires we specify the @TransactionManagement annotation (BEAN) in the class and we use the javax.transaction.UserTransaction interface. Within the business method, a transaction is initiated with "UserTransaction.begin" and confirmed (comitted) with "UserTransaction.commit". Here in Listing 1 is an example.

Listing 1. Example of how to initiate and confirm transactions.

  public class AccountSessionBean {
            @Resource Javax.transaction.UserTransaction tx;
            public float deposit() {
                     //. . .
                              //. . .
                     //. . .

Above we see the presence of @Resource note. This notation is used to declare a reference to a resource, such as a die, an enterprise bean or environment entry. The annotation can be specified in a class, a method or a field. The Accountiner is responsible for injecting references to declared resources @Resource and map this property in a JNDI resource. If there is more than one recuro being used with @Resource annotation should be grouped these statements in a @Resources note. So @Resource note only indicates that we should perform dependency injection in the class.

Accountiner-managed transaction is the default and requires do not specify any additional note in class. The EJB Accountiner implements all the low-level transaction protocols, such as “Confirmation Procotolo in Two Phases" (Two-Phase Commit Protocol) between a transaction manager and a database system or messaging provider.

A bean class using a Accountiner-managed transaction is similar to the code in Listing 2.

Listing 2. Example of a bean with Accountiner-managed transaction.

  public class AccountSessionBean {
            public float deposit() {
                     //. . .

There are no additional notes specified in the bean class or method. Changes to the underlying resources are all confirmed (Committed) or reversed (Rolled Back).

A bean with no session state using a Accountiner-managed transaction can use the @TransactionAttribute annotation to specify transaction attributes in the bean class or method.

Specifying the TransactionAttribute the bean class means that it applies to all applicable bean methods. The absence of TransactionAttribute in the bean class is equivalent to TransactionAttribute specification (REQUIRED) on the bean.

The @TransactionAttribute values and their meaning are defined in Table 1.




When called on the client's transaction context. If the client calls with a transaction context, then it behaves like REQUIRED. If the customer call without a transaction context, then the Accountiner throws a javax.ejb.EJBTransactionRequiredException.


If the client calls with a transaction context, then it is propagated to the bean. Otherwise, the Accountiner starts a new transaction before delegating the call to the business method and tries to confirm (commit) transaction when the business process is complete.


The Accountiner always starts a new transaction context before delegating the call to the business method and tries to confirm (commit) transaction when the business process is complete. If the client calls with a transaction context, the suspended transaction is resumed after the new transaction has been confirmed (commit).


If the client calls with a transaction context, then it behaves like REQUIRED. If the customer call without a transaction context, then it behaves like NOT_SUPPORTED.


If the calling customer with a transaction context, the Accountiner then suspends and resumes the transaction association context before and after the business method is called. If the customer call without a transaction context, then no context of new transaction is created.


The customer is obliged to call without a transaction context. If the client calls with a transaction context, then the Accountiner so it behaves like NOT_SUPPORTED.

Table 1. Set of allowed values for @TransactionAttribute.

In addition to the notes, the "Accountiner-transaction" element in the Deployment Descriptor can be used to specify the transaction attributes. The values specified in the Deployment Descriptor override or complement the transaction attributes specified in the notes.

Only attributes of transaction REQUIRED and NOT_SUPPORTED maybe used for Message-Driven Bean. A JMS message is delivered to the final destination after the transaction is confirmed (commited), so the customer does not receive the answer in the same transaction.

By default the methods designed to @PostConstruct, @PreDestroy, @PrePassivate and @PostActivate run in a transactional context unspecified. The EJB 3.2 specifies that for a bean with session state managed Accountiner with transaction demarcation, your methods may have REQUIRES_NEW and NOT_SUPPORTED attributes.

Asynchronous invocation

Each method of a session bean is invoked synchronously, ie the client is blocked until the processing on the server side is complete and the result is returned. A session bean can mark a method for asynchronous invocation, and a client can then invoke that method asynchronously. This returns control to the client before the Accountiner to send the instance to a bean.

Asynchronous operations must have a return type "void" or "Future". Methods with a return type "void" are used to a standard called "fire-and-forget." The other version allows the customer to retrieve a value of the result, but we must check for exceptions, or attempt to cancel any invocation in progress.

The @Asynchronous annotation is used to mark a specific method (in method level) or all methods (class-level) of the bean as asynchronous. Here's an example in Listing 3 a bean with no session state that is marked as asynchronous in-class level.

Listing 3. Example of a bean marked as asynchronous in-class level.

  public class MyAsynBean {
            public Future<Integer> sumNumbers(int n1, int n2) {
                     Integer result = n1 + n2;
                     return new AsynchronousResult(result);

The method signature returns Future and the return type is AsynchronousResult (Integer). AsynchronousResult is a new class introduced in the EJB 3.1 involving the result of an asynchronous method in a Future object. However, behind the scenes, the value is returned and sent to the client.

Adding any new method in this class will do automatically the asynchronous as well.

This session bean can be injected and invoked in any Java EE component as shown in Listing 4.

Listing 4. Example of access to created bean.

 @EJB MyAsynBean MyAsynBean;
  Future<Integer> future = MyAsynBean.sumNumbers(10, 20); 

The methods in the API Future are used to check the availability of a result, which is made using the "isDone", or cancel the execution with "cancel (boolean podeInterromperSeExecutando)."

The client transaction context does not propagate to the asynchronous business method. This means that the semantics of the REQUIRED transaction attributes in an asynchronous method are exactly the same as REQUIRES_NEW.

However, the propagation of security context behaves similarly to implementation of asynchronous and synchronous method.


The EJB Timer service is a managed Accountiner that allows callbacks are scheduled for time-based events. These events are scheduled according to a schedule based on the schedule after a period or at regular intervals.

Time-based events can be arranged in multiple ways: through automatic timers based on the metadata (specified with @Schedule) programmatically using TimerService, methods marked with @Timeout and Deployment Descriptors.

The first step to perform time-based methods is marking any method of bean with @Schedule. Here in Listing 5 an example.

Listing 5. Marking methods of bean with @Schedule.

  public class MyTimerExample {
            @Schedule(hour="*", minute="*", second="*/10")
            public void printTime() {
                     System.out.println(“Executing method.”)

In this code, the printTime method is called every twelfth every minute and every hour. @Schedule Also has fields "year" and "month" with a default value "*" indicates to execute this method every month of every year.

The EJB Accountiner reads the @Schedule annotation and automatically creates the timer.

Table 2 shows some examples and their meanings that can be specified by @Schedule.




1 am, 2 am and 10 pm every day of the year.


Monday, Tuesday, Wednesday, Thursday and Friday, at midnight (based on default values for hour, minute and second).

minute="30", hour="4", timezone="America/Los_Angeles"

Every morning at 4:30 according to the Los Angeles time.


The day before the last day of the month at midnight.

Table 2. Examples and meanings for @Schedule.

@Schedules can be used to specify multiple timers. We note that there is no need for a @Startup note here, as the life cycle methods are not required. Each application automatically redeploy will delete and recreate all timers.

We can easily create interval timers using ScheduleExpression.start and ScheduleExpression.end methods. We can also easily create single-action timer, specifying fixed values for each field as shown in the example below:

@Schedule(year="A", month="B", dayOfMonth="C", hour="D", minute="E", second="F")

Timers are not for real-time, since the Accountiner merges the calls to a call back method.

Thus, the time-out method (timed out) can not be invoked at exactly the time specified in the creation of the timer.

The Timer service allows programmatic creation and cancellation timers. We can create programmatic timers using the "createXXX" methods in TimerService. The method that will be invoked at the scheduled time may be the method "ejbTimeout" the TimedObject object. The following example in Listing 6One.

Listing 6. Creating timers programmatically.

  public class MyTimer implements TimedObject {
            @Resource TimerService ts;
            public void initTimer() {
                     if (ts.getTimers() != null) {
                              for (Timer timer : ts.getTimers()) {
                     ts.createCalendarTimer(new ScheduleExpression().hour("*").minute("*").second("*/10"),
                                        new TimerConfig("meuTimer", true));
                     public void ejbTimeout(Timer timer) {
                              //. . .

The initTimer method is a lifecycle callback to clean any timers created earlier, and then creates a new timer that fires every 10 seconds. The ejbTimeout method, implemented by TimedObject interface is invoked every time the time limit (timeout) occurs. The "timer" parameter in this method can be used to override the timer information on when the next timeout will occur, information on the self timer, and collect other relevant data.

We note that the timers are created in the life cycle callback methods, thus ensuring that they are ready before any business method in the bean is invoked.

EJB 3.2 introduces a new API that is Timer.getAllTimers, which returns all active timers associated with the beans in the same module where the bean caller is packaged. These include both timers programmatically created and automatically created timers.

The third way to create timers is a method that has the following signature: void() {. . . } Void or (Timer timer) {. . . }. Another way would be to note the method @Timeout, as shown in the example in Listing 7.

Listing 7. Noting the method @Timeout.

 public class MyTimer {
            //. . .            
            public void timeout(Timer timer) {
                     //. . .

The fourth way to create timers is marking a method for running on an expiration timer using the ejb-jar.xml file. For example, as the method of Listing 8.

Listing 8. Example of a method which will be made a timer.

 public class MyTimer {
            public void timeout(Timer timer) {
                     //. . .

We can convert the method "timeout" up on a timer method (timer) by adding the following fragment in the ejb-jar.xml (Listing 9).

Listing 9. Converting the previous method timer.


Timers can be created in beans without session state, Singleton beans, and Message-Driven Beans but not beans with session state. This feature may be added to future versions of the specification, but until the recent version 3.2 it is not allowed.

Timers are persistent by default and can be done programmatically not persistent. Here in Listing 10 an example.

Listing 10. Making a timer as not persistent.

ts.createCalendarTimer(new ScheduleExpression().hour("*").minute("*").second("*/10"),new TimerConfig("meuTimer", true));  

Alternatively, "timerConfig.setPersistent(false);" It can be used to make non-persistent timer.

Timers set by annotations can also be made as non-persistent. The following example in Listing 11.

Listing 11. Creating non-persistent timers using annotations.

@Schedule(hour="*", minute="*", second="*/10", persistent="false")
  public void printTime() {
            //. . .

Events based on timers can only be scheduled in the beans without session state and beans Singletons.

EJB Lite

The complete set of EJB features need not be required for all applications of a company. As explained above, the Web Profile offers a reasonably complete stack, composed of standard APIs, and is able to treat a wide variety of web applications.

Applications oriented Web Profiles will need to use transactions, security and other features defined in the EJB specification. Thus, EJB Lite is designed to meet this need.

EJB Lite is a minimum feature set EJB which in turn is complete. No new functionality is defined as part of the EJB Lite. EJB Lite is just a proper subset of all features of the full EJB. This allows the EJB API can be used in applications that are less unlike a typical application Java EE.

Table 3 shows the differences between EJB 3.2 Lite and EJB 3.2 full.

EJB 3.2

Lite EJB 3.2

Full API

Session beans



Message-driven beans



Java Persistence 2.0



Business Local Interface /No-Interface



3.x Remote



2.x Remote/Home component



2.x Local/Home component



JAX-WS Web Service endpoint



EJB Timer Service Not Persist



EJB Timer Service Persist



Invocations the asynchronous Session Bean Local



Invocations the asynchronous Session Bean Remote






Interoperabilidade RMI-IIOP



Bean managed transactions and managed by Accountiner



Bean managed transactions and managed by Accountiner



Embeddable API



Table 3. Differences between EJB Lite and Full EJB.

Invocations not persistent beans asynchronous session and the EJB Timer Service are the new additions EJB 3.2 Lite.

An application server fully compatible with Java EE is required to implement the full set of EJB features. Among these servers have Oracle Weblogic, JBoss and Glassfish.

Creating an Application with EJB Lite

First we must download a server that supports EJB Lite. One of these servers is Tomee.

The Tomee is a mixture of Tomcat with JavaEE. With Tomee we have Tomcat added and integrated with EJB, ready for use. The Tomee supports the following features:

  • CDI (Apache OpenWebBeans);
  • EJB (Apache OpenEJB);
  • JPA (OpenJPA Apache);
  • JSF (Apache MyFaces);
  • JSP (Apache Tomcat);
  • JSTL (Apache Tomcat);
  • JTA (Apache Geronimo Transaction);
  • Servlet (Apache Tomcat);
  • Javamail (Apache Geronimo JavaMail);
  • Bean Validation (Apache bVal).

To download the Tomee just visit site or download directly on the link

After downloading the Tomee just descompactarmos in any folder on your computer.

Now we can go to the Eclipse. Simply open the Eclipse and create a project of type "Dynamic Web Project", as shown in Figure 1.

Figure 1. Choosing a type Dynamic Web Project project.

After that, we must create a new server type Tomee. To do this, click on "New Runtime", as shown in Figure 2.

Figure 2. Selecting "New Runtime" to create a new server.

After that, we must select a project type "Apache Tomcat v7.0", as shown in Figure 3.

Figure 3. Selecting a project type "Apache Tomcat v7.0".

Then select the "Tomcat installation directory" the Tomee installation directory and finalized through the "Finish" (Figure 4).

Figure 4. Selecting the installed Tomee.

Finally, on the "Servers" added the server we just created (Tomee) so we can deploy the applications and start, stop or restart the server. To do this, click the right button on the "Servers" and click "New" and "Server", as shown in Figure 5.

Figure 5. Adding new server in the Servers tab.

On the next screen simply select the Tomee server created earlier and choose a name for the server, as shown in Figure 6.

Figure 6. Selecting the Tomee server created.

To illustrate the use of EJB and Tomee server that supports EJB Lite will create a project of an account as below.

First we must create a ejb package and a servlet package in "src". In EJB package will create the Account class that is implemented in Listing 12.

Listing 12. Exemplifying the EJB Account class that Accountins information regarding the Account.

 package ejb;
  import javax.ejb.Stateful;
  @Stateful(mappedName = "Account")
  public class Account {
         float balance = 0;
         public void deposit(float Value) {
               balance += Value;
         public void withdraw(float Value) {
               balance -= Value;
         public float getBalance() {
               return balance;

The Controller class will be our class driver that is responsible for calling the EJB and store information in the section. Here in Listing 13 code of the Controller class.

Listing 13. For example of the application controller.

 package servlets;
  import javax.ejb.NoSuchEJBException;
  import javax.naming.Context;
  import javax.naming.NamingException;
  import javax.servlet.RequestDispatcher;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.naming.*;
  import java.util.*;
  import example.ejb.Account;
  public class Controller extends HttpServlet {
         private static final long serialVersionUID = 1L;
         private static final String ACCOUNT_SESSION_KEY = "AccountStateful";
         HttpServletRequest request = null;
         protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               this.request = request;
               try {
                      Account Account = (Account) request.getSession().getAttribute(ACCOUNT_SESSION_KEY);
                      if(Account == null) {
                             Account = createEJB();
                      float deposit = 0;
                      if (request.getParameter("deposit") != null && !"".equals(request.getParameter("deposit")))
                             deposit = Float.valueOf(request.getParameter("deposit"));
                      float withdraw = 0;
                      if (request.getParameter("withdraw") != null && !"".equals(request.getParameter("withdraw")))
                             withdraw = Float.valueOf(request.getParameter("withdraw"));
                      if (deposit > 0)
                      if (withdraw > 0)
                      System.out.println("Account value:" + Account.getBalance());
                      request.setAttribute("Balance: ", Account.getBalance());
                      RequestDispatcher d = request.getRequestDispatcher("/index.jsp");
               } catch (IOException | ServletException e) {
               } catch (NoSuchEJBException n) {
                      try {
                      } catch (NamingException e) {
                      RequestDispatcher d = request.getRequestDispatcher("/index.jsp");
               } catch (NamingException e) {
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          processRequest(request, response);
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          processRequest(request, response);
      private Account createEJB() throws NamingException {
               Properties p = new Properties();
               p.put("openejb.home", "C:\\Users\\test\\Desktop\\proj_security\\apache-tomee-webprofile-");
               p.put(Context.PROVIDER_URL, "t3://localhost:8080");
               InitialContext ctx = new InitialContext(p);
               Account Account = (Account) ctx.lookup("java:global/TestEJBLite/Account");
               request.getSession().setAttribute(ACCOUNT_SESSION_KEY, Account);
               return Account;

In the code above the line "Account account = (Account) request.getSession().getAttribute(ACCOUNT_SESSION_KEY);." We keep in the session EJB Stateful used. If the account is zero creates a new EJB.

In the line "if(request.getParameter("deposit")!=Null && !"".eEquals (request.getParameter("deposit")))" and the lines below we see what was received form available to the user and make a deposit or a withdrawal on the account in the "request.setAttribute("balance", "Account.getBalance());" recorded in the section the current balance of our account. Finally, in the "RequestDispatcher d = request.getRequestDispatcher("/index.jsp");.. "redirect to the index page again with the updated balance. An important point to note is the exception catch" catch (NoSuchEJBException n) ". Normally applications treat this type of exception because it is possible that the session with the client remains active, but the EJB instance has been lost because the server was rebooted.

In business projects normally we use a EJB Stateful in specific cases, such as shopping sites where we should maintain the state of objects. However, we can also use sessions (HttpSession) so instead of using EJB. Overall, Stateful EJBs are more efficient to cache than HttpSession. HttpSession are best used for presentation logic, as Wizzards, navigation, validation, etc. Another practice widely used in the market is that we use a HTTPSession in our pages should use Stateless Session Bean to EJB, but to store EJB in HtppSession must use a Stateful Session Bean. This practice can become complicated if we use clusters, but can be managed. These are some of the discussions that take place when we use these practices in projects personally try to use HttpSession to store data in session and Stateless Session Bean for EJBs.

Here in Listing 14 the page of our sample application.

Listing 14. Home Account application.

 <%@taglib prefix="c" uri=""%>
  <%@page contentType="text/html" pageEncoding="UTF-8"%>
               <form name="f" action="/TestEJBLite/Controller" method="post">
                      <label>Choose Deposit or Withdraw</label>
                      <label>Ammount to deposit:</label>
                      <input type="text" id="deposit" name="deposit"/>
                      <label>Ammount to withdraw:</label>
                      <input type="text" id="withdraw" name="withdraw"/>
                      <input id="send" name="send" type="submit" value="Send"/>
               Current Balance: ${balance}

Finally, our web.xml file is configured as the code in Listing 15.

Listing 15. File web.xml of our application.

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">
    <display-name>Example FrontController</display-name>

How try homework to make several withdrawals and deposits into the account, and implement validations with beans or validation transactions through deposits and withdrawals. The best way to learn to use the new tools is to practice and EJBs is no different. From now with the application tip and settings above it is much simpler of using EJBs, especially after the end of the obligation of using file descriptors that required many settings.


G. Arun, What's new in EJB 3.2.

JSR-000345 Enterprise JavaBeansTM 3.2.

Fabrí­cio Galdino is a software expert and has worked with IT analysis and business development for more than five years. It has extensive experience with testing, back and front-end technologies.

What did you think of this post?
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
You must be logged to download.

Click here to login