http://www.developer.com/

Back to article

EJB 3.1: The EJB Application Gets Simpler, More Flexible


May 12, 2010

The Enterprise JavaBeans (EJB) 3.0 specification made the developer's life easier with simplicity-focused initiatives such as removing the home interface and ease-of-development features such as annotations. As a result, it was very well received and highly adopted by the enterprise Java developer community. The latest release of the spec -- EJB 3.1 -- makes development even simpler with conveniences such as making business interfaces optional, a feature that makes EJBs look very similar to a normal POJO.

Apart from that addition, EJB 3.1 introduced several other interesting features, such as Singleton beans, easy EJB packaging, asynchronous session beans, the ability to run EJBs in a Java SE environment, and the concept of EJB Lite.

In this article, I introduce these new features in EJB 3.1 and discuss each one with code examples. If you are new to EJB and want to learn more about the 3.1 version of the spec, this article can serve as a good starting point. EJB veterans will be able to appreciate the drill down on the new features.

Removal of Local Business Interface

EJB 3.0 made enterprise Java application development easier by introducing POJO-based development and removing home interfaces. EJB 3.1 goes one step further and makes even the business interface optional. Even though interface-based programming promotes good loosely coupled application development, interfaces often are written only when they are needed.

In EJB 3.1, session beans can be written as simple POJO-like message-driven beans and JPA entities, like this:

@Stateless
public class StockBean {
public double getStockPrice(String symbol) {
if (symbol.equals("ABCD")) {
return 2340.98;
}
if (symbol.equals("ZYXV")) {
return 654.45;
}
return 0.0;
}
}


Now when enterprise bean clients like Servlets try to access EJBs locally, they do not need an interface to access them. They can invoke the bean methods directly, like any other object method.

This feature also provides an opportunity for POJOs to be exposed as stateless session beans:

…………
…………
@WebServlet(name="StockServlet", urlPatterns={"/StockServlet"})
public class StockServlet extends HttpServlet {
   @EJB
   StockBean stockBean;
    
    protected void processRequest(HttpServletRequest request, 
HttpServletResponse response) throws ServletException,
IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String symbol="ABCD"; out.println(stockBean.getStockPrice(symbol)); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException { processRequest(request, response); } } ………… …………


As you can see, making business interfaces optional provides client-to-session-bean access without a separate local business interface. However, it is important to understand that business interface are optional only for local clients; remote clients require them.

Singleton Beans

EJB 3.1 also introduced a new type of bean, the Singleton bean. The primary goal of Singleton beans was to enable application-wide data sharing and to support concurrent access. With Singleton beans, the EJB specification now provides a flexible concurrency option.

By marking a session bean as Singleton, you share a single session bean instance between clients and enable it to support concurrent access. When a bean is marked as Singleton, the container guarantees a single instance per JVM that is shared across the application tier. This feature can be used for effective caching as well, as Singleton beans can cache state across the application tier.

Singleton beans, which are like any other EJB, are POJOs that are marked as Singleton beans with the @Singleton annotation. Optionally, the bean can be marked as a Singleton using a deployment descriptor. In effect, Singleton beans are like stateless session beans except that they are not pooled and there can be only one Singleton bean instance per JVM.

@Singleton
public class AccessCountBean {
    
    private int accessCount;
    public int getAccessCount() {
        return accessCount++;
    }
    public void setAccessCount(int accessCount) {
        this.accessCount = accessCount;
    }  
}


Flexible Concurrency

Singleton beans also pave the way for flexible concurrency options. All Singleton beans by default are transactional and thread safe, and they are never passivated. Concurrency is managed either by the container or by the bean, with the default concurrency manager being the container. The annotation @ConcurrencyManagement(CONTAINER) is used for container-managed concurrency, and @ConcurrencyManagement(BEAN) is used for bean-managed concurrency. EJB 3.1 introduces concurrency annotations to perform locked read and write operations on the getter and setter methods. Annotations like @Lock(READ) and @Lock(WRITE) are used to restrict the read/write access on the methods by concurrent clients.

Singleton beans help you maintain application state, similar to what the Servlet application scope object tries to do. Singleton beans are useful for sharing state across the application, when multiple threads are accessing the bean concurrently and when a bean must perform some tasks during application startup and shutdown.

EJB Components in WAR File

While annotations and optional deployment descriptors have significantly simplified the development and deployment of enterprise Java applications, the packaging structure of Java EE applications (see Figure 1) raised a problem. Developers had to place EJB components in a separate JAR file, and the file would be packaged along with the WAR file in an EAR file.


Figure 1. Post List Page with Tags:
This is how packaging was done prior to EJB 3.1.

EJB 3.1 provides a simplified packaging mechanism for web applications including EJBs. EJB 3.1 provides an option to package EJBs directly in the WAR file itself instead of creating a separate JAR file. Developers can place EJBs in the same folder where the web component classes -- Servlets -- are placed, under the WEB-INF\classes directory of a WAR file. Figure 2 shows the packaging in EJB 3.1.


Figure 2. EJB 3.1 Packaging Structure:
Here is packaging in EJB 3.1.

Asynchronous Session Bean

Enterprise applications typically require asynchronous processing. Message-driven beans were introduced in EJB 2.0 to support asynchronous invocation in a simplified way. However, before using message-driven beans, you must set up other criteria such as messaging systems and the JMS API.

Until EJB 3.1, session bean invocations were always synchronous, irrespective of whether the session bean was local or remote or had no interface invocation. When a client invokes a method on the session bean, the client call is blocked for the duration of the invocation. The control is released after all of the processing is complete. Beginning with EJB 3.1, a session bean can support asynchronous method invocations. Some methods can be marked as asynchronous in the session bean. Bean methods annotated with @Asynchronous are invoked asynchronously. When a client invokes a method marked as @Asynchronous, the container returns control to the client immediately and the processing of the invocation is handled on a separate execution thread.

Asynchronous methods return a void or Future<V> object of the java.util.concurrent API. Most of the requirements for asynchronous processing will have the return type of the method as void. For a method that is expected to have a return value, the Future<V> object is returned as a result value. The Future<V> API (V is the result value of the asynchronous invocation) will allow the client to get the status of the invocation, retrieve the return value of a method, check for an exception, or even cancel the invocation.

If the client receives an exception, it is understood that the container will not be able to service the request for the asynchronous method and the client should try invoking the method again. However, if no exception is received, then the client can expect a return value from the container because of the asynchronous method invocation, which usually will be the Future<V> object.

EJB Lite

The EJB specification has large set of features for developing a wide variety of enterprise applications. Many enterprise applications do not require the complete set of these features and do not use the full range of EJB APIs. So, EJB 3.1 introduced EJB Lite, a minimal subset of EJB APIs that still includes all the required features for creating an enterprise application.

A carefully selected collection of simple yet powerful EJB features -- without any specialized APIs -- EJB Lite provides vendors with the option to implement a subset of EJB APIs within their products. Applications created with EJB Lite can be deployed in any server that supports EJB technology -- whether it is full EJB or EJB Lite. Embeddable containers support EJB Lite as well.

EJB Lite has the following subset of EJB APIs:

  • Session bean components
    • Stateless
    • Stateful
    • Singleton session beans
  • Supports only synchronous invocation
  • Transaction
    • Container-managed transaction and bean-managed transaction
  • Security
    • Declarative and programmatic security
  • Interceptors
  • Support for deployment descriptor (ejb-jar.xml)

EJB Lite offers simple and lightweight implementations. It allows you to develop applications with more annotations and much less configuration. The table in Figure 3 summarizes the features supported in the full EJB 3.1 API and in EJB Lite.


Figure 3. EJB 3.1 Full and EJB Lite Feature Comparison:
EJB Lite has a subset of the EJB APIs.

Executing EJB in Java SE Environment

EJB 3.1 has an embeddable API that allows EJBs to run in Java SE environments (i.e., the client and the EJB run in the same JVM and class loader). The benefits of having an embeddable API include:

  • Better support for testing
  • Batch processing
  • Usage of the EJB programming model in desktop applications

To run EJBs, EJB 3.1 provides an embedded EJB container and uses JNDI for lookup. The embeddable EJB container provides an environment to manage EJBs with support for a limited set of services. The javax.ejb.EJBContainer class represents an embeddable container.

Conclusion

The new features introduced in EJB 3.1 bring a lot of advantages to developing enterprise Java applications with EJBs. With the promising features discussed in this article, EJB 3.1 is bound to attract the same developer community support that EJB 3.0 did.

Acknowledgements

The authors would like to sincerely thank Mr. Subrahmanya (SV, VP, ECOM Research Group, E&R) for his ideas, guidance, support and constant encouragement and Mr. Nitin KL for kindly reviewing this article and providing valuable comments.

About the Authors

Sangeetha S. works as a Senior Technical Architect at the E-Commerce Research Labs at Infosys Technologies. She has over 10 years of experience in design and development of Java and Java EE applications. She has co-authored a book on 'J2EE Architecture' and also has written articles for online Java publications.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date