Meera has posted 70 posts at DZone. You can read more from them at their website. View Full User Profile

EJB 3.1 – EJB New and Improved!

  • submit to reddit

The EJB 3.0 specification was a huge improvement from what we were used to in the early versions of EJB. Available as an early draft, EJB 3.1 has many more features and is even easier to use.

Let’s take a brief overview of a few interesting topics being considered in this new and improved version of EJB.

Optional Session Bean Business Interfaces:

Writing enterprise applications using EJB 2.1, EJB 3.0 or Spring always promoted the idea of writing component interfaces.  In many cases, you could do with just a POJO without an interface. This new version of EJB allows you to write Session beans with no interfaces; just like you write your JPA entities and Message Driven beans. So, let’s see an example of how this can be accomplished:


import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;

import ejb31.samples.entity.Customer;

public class CustomerManager

public Customer getCustomer()
Customer customer = new Customer();
return customer;


Global JNDI Names:

I remember blogging about the issues I had to face due to the portability issues caused by vendor-specific JNDI names. I had to work around a solution for testing on three different application servers: JBoss, Oracle and GlassFish. Each of these application servers has completely different naming convention for remote interfaces.

The GlassFish AS uses the fully qualified name of the remote business interface as default: 

Object obj = initialContext.lookup("com.os.ent.CustomerManagerRemote");

JBoss on the other hand uses the application (EAR) name, followed by the EJB name and followed by a ‘/remote’ constant.

Object obj = initialContext.lookup("ejb3sampleapp/CustomerManager/remote");

Oracle uses the name specified in the @Stateless annotation.

Object obj = initialContext.lookup("CustomerManager");

In EJB 3.1, the global JNDI names would follow a standard pattern that is portable across all the different application servers: 


Singleton Session Beans:

In all the earlier versions of EJB’s, we could use two session bean types: Stateless and Stateful. With EJB 3.1, we have the one which many of us felt a need for from time-to-time called the Singleton. Yes, Singletons are POJOs just like our Session beans, and the container is guaranteed to maintain a single shared instance of this Singleton. These Singletons are thread safe and also transactional. Like all other EJB’s, singletons have all the services such as security, remoting, dependency injection, web services, interceptors and so on.

package ejb31.samples.singleton;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Singleton;

public class StateRegistryBean implements StateRegistry {

private final Map<String, String> states = new HashMap<String, String>();

public Collection<String> getStates() {
return new ArrayList<String>(states.values());

public void removeState(String state) {

public void setState(String name, String value) {
states.put(name, value);



Calendar Based Timer Services:

One of the most important changes in EJB 3.1 is the ability to declaratively create cron-like schedules to trigger EJB methods. All that is needed is to annotate an EJB method with the @Schedule annotation to implement the timer.
For example the following schedule represents "Every Monday at 6:15": @Schedule(minute=”15”, hour=”6”, dayOfWeek=”Mon”) send a weekly newsletter to everyone in the list:

Public class NewsLetterBean
@Schedule(minute=”15”, hour=”6”, dayOfWeek=”Mon”)
Public void sendNewsLetter()


Asynchronous Session beans:

In many enterprise applications I was involved, asynchronous processing was a must. And the only way to accomplish this was by using Message Driven Beans.  Even though writing MDBs was very trivial, configuring all the necessary server resources like connection factories, topics and queues made it a little bit of a chore, especially since all I needed was an asynchronous method invocation.
With EJB 3.1 these issues are easily solved by a simple annotation placed on the Session Bean: @Asynchronous. Under normal circumstances, a Session bean method call blocks the client for the duration of that call. With this annotation in place, the container returns control to the client and executes the method on a separate thread.
The Session bean method call which is annotated with the @ Asynchronous annotation can return a java.util.Future object that allows the client to retrieve a result value, check for exceptions, or attempt to cancel an in-progress invocation.

EJB Lite:

A vast majority of clients I have worked with recently use EJB applications. Most of them use injection, JPA, stateless session beans and transactions, but not necessarily messaging, remoting or web services. EJB Lite is perfect for such applications. The best part of EJB Lite is that you can write your enterprise application with no XML at all, and knowing a very small number of basic annotations.
The following is a list of features proposed for EJB Lite:
•    Stateless, Stateful, and Singleton session beans
•    Only local EJB interfaces or no interfaces
•    No support for asynchronous invocation
•    Interceptors
•    Declarative and programmatic security
•    Declarative and programmatic transactions
•    No support for Timers and scheduling

Easy packaging:

Even for the simplest web application, EJB 3.0 required that we have the components of the web application in a war file, EJB’s packaged in a jar file, and this war and jar in turn be packaged into an ear and deployed. This is very cumbersome, especially for new-comers to Java EE.
This isn’t the case anymore, all you would need to do is to drop all your EJB’s within the WEB-INF/classes directory and deploy these along with your web application.
If you have an ejb-jar.xml file, which again is optional, it would be placed within the WEB-INF directory just like the web.xml file.

EJB 3.1 Embeddable Container:

Testing EJBs was a herculean task all these years. It isn’t anymore with the timely and useful innovation of the embeddable container. The embeddable container allows you to use JPA and EJB 3.1 outside a container.  There are already a number of open source embeddable EJB 3 containers that can run in any Java SE environment. To name a few: Open EJB, GlassFish, JBoss. For unit testing as well as running all the examples included in this article, I used Apache OpenEJB communities latest release of OpenEJB 3.1. OpenEJB is an embeddable, lightweight EJB 3.0 implementation with partial support of EJB 3.1.
Let’s take a look at how I was able to successfully test my Singleton Beans. The listing below shows the test class.


package org.ejb31.samples;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import junit.framework.Assert;

import org.junit.Test;

import ejb31.samples.singleton.StateRegistry;

public class StateRegistryTest {

	public void testStates() throws Exception {
		Properties props = new Properties();

		InitialContext context = new InitialContext(props);

		StateRegistry stateOne = (StateRegistry) context

		StateRegistry stateTwo = (StateRegistry) context

		stateOne.setState("MaryLand", "MD");
		stateTwo.setState("Virginia", "VA");
		Assert.assertEquals(2, stateTwo.getStates().size());
		Assert.assertEquals(stateTwo.getState("MaryLand"), "MD");
		Assert.assertEquals(stateOne.getState("Virginia"), "VA");



In the above test class, the org.openejb.client.LocalInitialContextFactory used as the JNDI provider, will automatically embed OpenEJB into the testing VM. The same instance of OpenEJB is used for all the tests within that VM.

And below is the output from within the Eclipse IDE when you run the above test:

Apache OpenEJB 3.1    build: 20081009-03:31
INFO - openejb.home = C:\dev\ejb3.1\samples
INFO - openejb.base = C:\dev\ejb3.1\samples
INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)
INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)
INFO - Found EjbModule in classpath: C:\dev\ejb3.1\samples\build
INFO - Beginning load: C:\dev\ejb3.1\samples\build
INFO - Configuring enterprise application: classpath.ear
INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)
INFO - Auto-creating a container for bean StateRegistryBean: Container(type=SINGLETON, id=Default Singleton Container)
INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)
INFO - Auto-creating a container for bean HelloBean: Container(type=STATELESS, id=Default Stateless Container)

INFO - Configuring PersistenceUnit(name=DemoPU)
INFO - Configuring Service(id=Default JDBC Database, type=Resource, provider-id=Default JDBC Database)
INFO - Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'DemoPU'.
INFO - Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)
INFO - Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'DemoPU'.
INFO - Adjusting DemoPU <jta-data-source> to 'Default JDBC Database'
INFO - Adjusting DemoPU <non-jta-data-source> to 'Default Unmanaged JDBC Database'
INFO - Enterprise application "classpath.ear" loaded.
INFO - Assembling app: classpath.ear
INFO - PersistenceUnit(name=DemoPU, provider=org.apache.openjpa.persistence.PersistenceProviderImpl)
ERROR - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a
ClassFileTransformer which requires a JavaAgent.  See
INFO - Jndi(name=StateRegistryBeanLocal) --> Ejb(deployment-id=StateRegistryBean)
INFO - Jndi(name=HelloBeanRemote) --> Ejb(deployment-id=HelloBean)
INFO - Created Ejb(deployment-id=HelloBean, ejb-name=HelloBean, container=Default Stateless Container)
INFO - Created Ejb(deployment-id=CustomerManager, ejb-name=CustomerManager, container=Default Stateless Container)
INFO - Created Ejb(deployment-id=StateRegistryBean, ejb-name=StateRegistryBean, container=Default Singleton Container)
INFO - Deployed Application(path=classpath.ear)

I haven't seen anything as easier than this to run tests against EJB's. 


I, like most developers, dreaded working with EJB 2.x. EJB 3 was a big step in the right direction. I myself was involved in writing a couple of enterprise applications in EJB 3.0, which I greatly enjoyed. With this latest, not yet released EJB 3.1 version, it took me less than an hour to explore all the examples shown in this article. I used OpenEJB 3.1 for this article and was even able to test some of the examples as shown above.

What are your thoughts about this upcoming version of EJB? Have you tried using EJB 3.1? The expert group in my opinion has done a tremendous job, what do you think?

You can also send your feedback directly to the expert group at In case you like to know more about EJB 3.1, you can take a look at the EJB 3.1 public draft.


Published at DZone with permission of its author, Meera Subbarao.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Reza Rahman replied on Thu, 2008/12/04 - 9:53pm in response to: Reza Rahman


OK, I just heard back from a number of people I respect about this and they confirmed exactly what I have been feeling -- *I* have devaluated the hard work Meera and the EJB 3.1 EG has put in by allowing myself to get dragged into a pointless shouting match just because of my familiarity with Spring.

I really should have used more discipline and asked questions about what the use case, importance and frequency of any requested feature is without further comment on the merits on any other competing technology or my experience with it (the true key elements to developing any software worth its salt).

Unfortunately, I do have to say I have not garnered anything all that useful for EJB 3.1, WebBeans or Java EE 6 so far. However, I'll continue to keep my ears to the ground on this thread as long as it is active…

As much as many people appreciate the simplicity of Java EE 5, I still deal with numerous poor souls having a hard enough time learning Java EE 5 for the job or to get a certification. The last thing I want to do is make the learning curve more difficult for these folks. If that means we loose some kind of weapons race in some people’s minds, so be it.

In fact, I worry that WebBeans has already allowed itself to go too far down this path. That being said, I do think it is an important specification with much to offer and with many very smart people working on it including Gavin King of Red Hat and Bob Lee of Google.

Best regards,

Reza Rahman replied on Thu, 2008/12/04 - 11:24pm in response to: Roman Pichlik


[quote=rp117107]This code shows you, how dynamically introduce a new implementation without tightly coupling between provider and consumer and it is absolutelly must if you are going to provide some extension points in your API.[/quote]

Before we go too far down the lines of product comparisons, let's take a little more discipled approach to this. Have you actually done this for a real-life production application? If so, can you tell me a little more about the specific real-life application? How often is this solution needed? Do you think there are other ways of accomplishing the same thing that are sufficient?



Reza Rahman replied on Thu, 2008/12/04 - 11:28pm in response to: Bhaskar Karambelkar


Let's revisit this discussion starting from my last post if that's OK. Clearly, you disagree with me that some of the features I mentioned are not that useful. Can you give me specific real-life examples of which of these features you have used and why?

Thanks in advance,


Reza Rahman replied on Thu, 2008/12/04 - 11:31pm in response to: Per Olesen


[quote=pulesen]I use JDK timers and task executors.[/quote]

Care to share why so? What real-life solutions have you used them for? How often does it happen? Why wasn't Quartz sufficeint for these cases?



Roman Pichlik replied on Fri, 2008/12/05 - 4:47am in response to: Reza Rahman

Have you actually done this for a real-life production application? If so, can you tell me a little more about the specific real-life application? How often is this solution needed?

Reza, you are asking me about respect, but you have not enough respect to me! Do you think that i'm kidding you? Becuase this is real-life application requirement. My experience comes from seven years of real life enterprise development and bunch of consultation that i did. Maybe you are right, it's my personal feeling, but based not only on my experience. I spent last two years of developing leading SOA Governance product and trust me it's the large project (180+ Maven projects, 60+ Spring contexts, over hundreds of managed objects (beans) , EAR (6 x WAR modules, 2 x EJB modules), deployment on Oracle, MSSQL, DB2 + WebSphere, OAS, JBoss, Weblogic ).

Reza Rahman replied on Fri, 2008/12/05 - 10:27am in response to: Roman Pichlik


[quote=rp117107]but you have not enough respect to me[/quote]

I assure you, that's not the intent here and I will try my best to avoid any such sentiment. Lack of mutual respect is never helpful...

That being said, I will have to ask you to bare with me, given what is at stake here and how many people this can impact. As I mentioned, it is really critical to pin down how important this feature really is and how frequently it is needed in realistic situations and not just on paper. To get to that, I really need a little more information  from you. Unfortunately this is applying to a large majority of the Spring-specific features you mentioned (constructor injection, factory methods, collections injection with type safety, non type-safe injection) vis-a-vis EJB 3.0/3.1 specifically with WebBeans in distant scope. Although these are and will likely be supported,  am really not convinced they are critical to a majority of applications.

[quote=rp117107]Maybe you are right, it's my personal feeling[/quote]

Glad you are acknowledging this possibility.

Thanks in advance for your patience...



Reza Rahman replied on Fri, 2008/12/05 - 11:19am in response to: Reza Rahman


Just to make sure, what I am asking for is not specific to anyone and not personal in any way. As some good people rightly pointed out to me, ultimately this is all about doing the right things for the right people. There is no room for ego here.

One value of any good standards process is to guard against the tendency towards bloated features in the name of competetive advantages that all vendors, and not just SpringSource tend to lean towards to "sell" what they have. Nowhere is this more patently obvious than in the super-heavywight application servers in the past that we are solidly backing away from in Java EE 6, and have to a great degree in EJB 3.0.

For example, OpenEJB 3.1 is just over 14 MB as a downlaod today, *fully functional* and with *all dependencies*, even with EJB 2.x legacy support. That is the overall direction the Java EE 6 EG is taking and I think it is the right direction, especially with things like EJB 3.1 Lite. 

Best regards,


Otengi Miloskov replied on Fri, 2008/12/05 - 11:32pm

Reza, I respect you a lot but Roman is just asking a plain comment comparision of his Spring code with a EJB3.1 code, Im not familiar with EJB3.1 yet but if I can I could write it down now is simple just put the comparison and be done this thread,It is pretty simple question to compare how stack against right now Spring and EJB3.1. If you feel difficult to post a tiny code as Roman did in this thread for comparing, it means that EJB3.1 is still complex and need IDE and tooling to write some code.


Otengi Miloskov replied on Fri, 2008/12/05 - 11:39pm

With Spring I dont need IDE, I could use notepad and it is for real. What about EJB3.1?. As for example when I write a class for a webservice in Python or PHP I use Textmate, I dont use IDE for it. Java with Spring is getting close to that, what about JEE? if still need IDE it means is complex and we dont want that anymore. The IDE should be used for Refactoring and manage a big project but for writing code a text editor should be enough but if the API does not let you to do it that way it means is complex and it is getting in your way. Drop that or it will be another EJB2, CORBA, MFC and all the crappy technology have been in IT history.

Kenneth Mark replied on Sat, 2008/12/06 - 4:57am

It is really unfortunate turning this thread into (again again and again) JEE vs Spring war.

I though, for good to Java comunity, that was over.

I like spagethi and my wife love chinese noodle and that's all !


Reza Rahman replied on Sat, 2008/12/06 - 11:19am in response to: Otengi Miloskov


You are missing the point. I believe the features being insisted upon are pure bloat with no practical value in the first place. By definition, this adds needless compexity to any software. That is what I see as fundamentally wrong with Spring and even to some degree WebBeans.

None of the discussions so far pertain to IDE vs. non-IDE. There is no reason Java EE 5 code should bind you to an IDE. Indeed, my co-author Debu Panda uses nothing but UNIX command-line tools for his code.



Reza Rahman replied on Sat, 2008/12/06 - 11:07am in response to: Otengi Miloskov


As I noted, there is no need to use any graphical tools with Java EE 5. Indeed, GlassFish has taken many pains to make sure the graphical console it provides is optional, just as JBoss does.



Reza Rahman replied on Sat, 2008/12/06 - 11:26am in response to: Kenneth Mark


Thanks for taking the time to state this. Some of the absolutist mind-sets are indeed regrettable and outdated if not a little dangerous. That being said, in a lot of cases they are simply a result of being honestly misinformed.

In fact, I believe there are excellent use-cases for EJB 3-Spring integration. I have recently presented on this very topic. The presentation is here: and it includes sample code written with OpenEJB 3.0 and Spring 2.5. As I see it, it is a great way of freeing yourself from being married to either technology and making use of the advantages of both.

As such, I personally would have no problems with a comparison discussion any time, anywhere if it can be carried out in a calm, rational manner without religious zeal and hidden agendas to prove "absolute superiority". Sadly, my personal experience is that quite the opposite is true. I believe some of the tonality in this thread is more of the same.



nitin pai replied on Tue, 2008/12/09 - 12:54am

Has this discussion ended or being continued in a separate thread?

I still don't see the code comparison done instead of constant arguments. Bring down the code folks.

Per Olesen replied on Tue, 2008/12/09 - 2:56am in response to: nitin pai

@nitin pai:

Has this discussion ended or being continued in a separate thread?

I still don't see the code comparison done instead of constant arguments. Bring down the code folks.

It has not been continued in a separate thread to the best of my knowledge, nor should it. I am not sure if it has ended.

Personally, I am convinced that further argumentation is pointless, until some of the EJBs gurus show us some code. Just tossing out questions as answers, when facts and real code is what we need and ask for, has no real value other than paint a muddy picture saying "sure, it can be done, ... but I know you don't want to, so I won't show you".

Roman Pichlik replied on Tue, 2008/12/09 - 3:46am in response to: Per Olesen


@nitin pai:

Has this discussion ended or being continued in a separate thread?

I still don't see the code comparison done instead of constant arguments. Bring down the code folks.

It has not been continued in a separate thread to the best of my knowledge, nor should it. I am not sure if it has ended.


Don't worry, i'll do it here on Java DZone.

Reza Rahman replied on Tue, 2008/12/09 - 12:59pm

This is the *last* time I am going to state this, so kindly either listen carefully or feel free to keep talking to yourself... 

I thought I made this painfully clear - I am more interested in establishing *why* a particular feature should be introduced into EJB in the first place. Indeed, this is the *first* question any responsible person developing *any* product would ask.

As I see it, a *robotic* point-to-point comparison of existing EJB 3 or Spring features is of little *practical* value and is mostly of *academic* interest. I'm all for helping others, but I too have limits of time and patience...

That being said, feel free to express an interest in such a comparison. I and many others have done it in the past and it's certainly the right time for an update once EJB 3.1 and WebBeans is finalized.

Kindly do not *presume* that I have some sort of obligation to entertain your personal interests. I only wish I had the luxury of time for that!

Best regards and thanks for you cooperation in keeping this a useful discourse.


Roman Pichlik replied on Wed, 2008/12/10 - 10:26am in response to: nitin pai

Separate thread

Reza Rahman replied on Wed, 2008/12/10 - 11:49am

OK, I'll try to participate if and when time permits. At this point, that is unfortunately looking unlikely given the number of more urgent things I have on my plate, including getting timely feedback to the EJB 3.1, JPA 2.0, WebBeans and Java EE 6 EGs (not to mention my responsibilties to clients as a consultant).

Sorry I can't indulge this right now and best regards.



P.S.: I am *always* available via email at if *anyone* needs a quick thought or comment on *anything* ("hate mail" not welcome :-)). I'm also usually active on the JavaRanch EJB forums for EJB specific topics as well as on the Manning author online forum for EJB 3 in Action (EJB 3/book specific).

hookfi john replied on Sun, 2009/05/31 - 7:47am

This article is about EJB3.1. Not Web Beans. I find it strange, that the EJB-spec, which should be enough to model the business logic in my application, will let another Web Beans spec take care of the real interesting DI tiffany with.Discounted Tiffany & Co silver jewelries are provided in our Tiffany’s online outlet store Tiffany Earrings,Tiffany Necklaces.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.