Java Champion / JavaOne Rockstar Adam Bien (adam-bien.com) is a self-employed consultant, lecturer, software architect, developer, and author in the enterprise Java sector. He is also the author of several books and articles on Java and Java EE technology, as well as distributed Java programming. adam has posted 59 posts at DZone. View Full User Profile

Why I Like EJB 3.0 And Really Like EJB 3.1

06.15.2008
| 11401 views |
  • submit to reddit

Marc Fleury wrote a readworthy Blue Paper "Why I Love EJBs" in 2002 (download), which for that time was really surprising. I was already working with EJBs at the time, but didn't really love them much :-). I wouldn't go quite as far as saying "love" now either, but I really like EJB 3.0. The reasons are:

  1. The performance overhead is low. In Glassfish v2 only about 3%.
  2. EJB 3.0 are thread save. This is a huge benefit. Every thread gets an own instance - also all injected resources (Entity Manager, Data Source, JMS) are thread save as well. The best of all: the container manages the resources for you. Only an annotation is required (@EJB for EJBs, @PersistenceContext for Persistence and @Resource for remaining resources :-)). Just try it with "plain old Web Container" :-). Hint: Servlets are thread-unsafe singletons.
  3. EJB 3.0 are transactional. So in case the method invocation is successfull, all resources will be synchronized (data written to DB, messages sent to server). The container does it for you - you have only know what you would like to achieve (this is platform independent, but sometimes hard enough :-))
  4. In all of my projects we get rid of deployment descriptors and used annotations. Only a lean persistence.xml was deployed. Refactoring, deployment and portability just worked well.
  5. EJB 3.0 are really portable (and so vendor, framework neutral). There is lot more specified, than EJB 2.1 days - so proprietary deployment descriptors aren't needed any more. Actually no descriptors are needed. You only have to deploy one clean jar, with persistence.xml in meta-inf. Everything else is optional (and somehow suspicious).
  6. The synergy between Convention Over Configuration (or officially: Configuration By Exception) and Dependency Injection is great. Actually in most cases you get with EJBs less code, than without (no "new" invocations, just declarations).
    @Stateless
    public class SampleBean implements Sample {
    @PersistenceContext
    private EntityManager em;

    @EJB
    private Another anotherBean;
  7. Getters And Setters are optional: for EJBs, as well as for JPA. It's your decision. Resources can be directly injected into the fields.
  8. The defaults and annotation configuration can overruled by XML-descriptors. The XML descriptors do not have to be complete - only interesting portions can be specified. You can easily override the production settings for e.g. staging (test, integration etc).
  9. Actually there is no special tooling required. You only need the annotations, a Java 6 compiler and a Jar. However the support in IntelliJ, Eclipse (with 500 additional plugis :-)), or Netbeans 6.1 are really superb. The applications servers are already well integrated - deployment, undeployment, configuration etc. can be managed directly from the IDE.
  10. EJB 3.1 will be embeddable out-of-the box. However Glassfish v3 is already emeddable. I'm testing now the WebContainer - it's surprising (starts in 500ms). JBoss is embeddable as well.
  11. EJB 3.1 will come with a lot of useful features: Singletons (good for configuration, startup classes etc.), better timer support (cron-like), async methods with Futures, optional local-interfaces and WAR-deployment.
  12. Pool settings and thread pool configuration is really useful to control the scalability (and not scale indefinitely until the container crashed :-))
  13. They play well with scripting (JavaScript, Groovy etc.)
  14. EJBs are managable and monitorable by default. You just deploy them into container - and you can monitor the method invocations, performance etc.
  15. No additional frameworks, libraries etc. are needed first. The ejb-jar and the container only contains your application code. So NoClassDefFoundErrors, ClassCastExceptions etc. can be minimized.
  16. EJB 3.0 are ultra-lean. You actually cannot take something away :-). However: I'm open for suggestions.
  17. They are really easy to test - it's just class with an interface. You can even start them outside the container.
  18. Even simple use cases can be efficiently be realized with EJB 3. See e.g. CRUD:
    @Stateless
    public class CrudServiceBean implements CrudService<Integer,Customer> {

    @PersistenceContext
    private EntityManager em;

    public Customer create(Customer t) {
    this.em.persist(t);
    return t;
    }

    public void delete(Customer t) {
    t = this.em.merge(t);
    this.em.remove(t);
    }

    public Customer find(Integer id) {
    return this.em.find(Customer.class, id);
    }

    public Customer update(Customer t) {
    return this.em.merge(t);
    }
    }
  19. ...and they really work well: I'm using EJB 3.0 + JPA 1.0 since about 2 years in projects. It worked not only surprisingly well for me - the team members were surprised as well.

However there is still room for improvement in the Java EE 6 Platform. JMS spec could be easily redesigned to be more "fluent". The JNDI registry is archaic. Fixing/simplifying the JNDI-API would be really beneficial not only to EJBs, but for the whole platform as well...

From http://blog.adam-bien.com/

Published at DZone with permission of its author, adam bien.

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

Comments

Jakob Jenkov replied on Sun, 2008/06/15 - 8:34am

In my opinion the community has pretty much left the idea of distributed objects in favor of larger grained distributed services. No matter how much EJB is patched the technology is just odd from the ground up. Most of the advantages you mention there are things that make EJB more like normal classes. But why use EJB at all then? I have met only one major reason for using EJB's: Transactions. But Spring has a reasonably elegant solution to that issue. JPA was a step in the right direction regarding persistence, but simple API's can do just as well. For instance, the CRUD stuff can be done easily with simple persistence tools. Just exactly what is it that EJB's do better than POJO's?

 

What I really DON'T like about EJB is that they have to run in a container.  

JeffS replied on Sun, 2008/06/15 - 11:33am

Entity Beans do not have to run in the container, session beans do, just for clarification.

Also, EJB 3.0 annotations are far more attractive, elegant, mainainable, and easier than Spring XML descriptors.  Spring now (finally) supports annotations, but how good it's support is I can't say.

Finally, Adam's list is excellent.  There is a whole lot of stuff that is fully taken care, that is "just there", in EJB 3.0, which would otherwise have to be wired in (read, xml config) with Spring.  This has huge value.  In other words, EJB gives you everything out of the box, easily, where as Spring is more of a "do it yourself" kit. 

PJ Murray replied on Sun, 2008/06/15 - 12:40pm in response to: Jakob Jenkov

[quote=jj83777]

In my opinion the community has pretty much left the idea of distributed objects in favor of larger grained distributed services.

[/quote]  

I agree, EJBs are not the appropriate level of granularity most applications and certainly not the right level for any service-oriented architectures.

Artur Karazniewicz replied on Sun, 2008/06/15 - 3:18pm

Adam

This is great summary how, EJB 3, and upcoming EJB 3.1 got better; however I can do exactly the same, just using my Tomcat and spring, spending less time, probably. Every single thing mentioned above. I don't need whole J2EE server overhead when I just want deploy JAX-WS webservice, or, simply web-app. I do still like use all the above goodies, however. Spring provides this OOTB simply with Tomcat, or even JETTY. Moreover - I still cannot simply test my EJB outside the container, since I can't have get EJB 3.0 DI without all the overhead (sure I can pick embedded GlassFish or JBoss, but then my portability is gone, right?). Also, even though, I see few things missing:
  • Convenient testing support (see, spring-test module)
  • AOP (Interceptors are not AOP)
  • Injecting other things than just EJB artifacts
  • Notion of component scopes (even plugabble)

Jakob Jenkov replied on Sun, 2008/06/15 - 3:54pm

annotations for configuration dependency injection is not a good solution in my opinion. It is just not flexible enough. I don't even find Spring XML flexible enough! I don't want to hardwire injection information into classes. What is injected into where is an external responsibility and should be managed externally. But even if I disagree with this list I have not voted it down. The story says "why I like EJB 3.0" and it tells so just fine. That I disagree does not make the text bad.

Ryan Developer replied on Sun, 2008/06/15 - 8:04pm in response to: Jakob Jenkov

What I really DON'T like about EJB is that they have to run in a container. 

 

How can you say this?  Spring IS a container.  Without the Spring container, you would have no DI or AOP.  Same thing with EJBs.  Like Spring, the EJB container can be used outside of an app server, or in Tomcat.  See OpenEJB.

 

 

Ryan Developer replied on Sun, 2008/06/15 - 8:17pm in response to: Artur Karazniewicz

Injecting other things than just EJB artifacts

To use Spring DI, you first have to make the class you want to inject a Spring bean by adding it into the Spring xml config file.

To use EJB DI, you first have to make the class you want to inject an EJB by adding it into the xml deployment descriptor, or using the @EJB annotation.  The difference is with EJB 3.0, that POJO must have an interface.   This restriction will be gone in EJB 3.1.   Also, EJB doesn't do things like let you configure DI with factories, constructors, etc.   I've suggested these enhancements to the EJB 3.1 expert group.  We'll see what happens.  I know the WebBeans JSR is complementary to EJB, and has very sophisticated DI capabilities.

 

AOP (Interceptors are not AOP)

Interceptors are AOP, but are less sophisticated.  Basically you only get ArroundInvoke, and it doesn't have as sophisticated a way to describe pointcuts.  Do you use Sprint AOP for anything other than transactions and security?  Like what?

 

 My biggest beef with EJB 3.0 was that it has to live in a separate project, and be packaged inside of an EAR to be used with a web project.  Thankfully this will finally be changed in EJB 3.1. 

Jakob Jenkov replied on Mon, 2008/06/16 - 1:24am

It seems a lot of things are "fixed" in EJB 3.1. But still, to me it seems like EJB is moving towards ordinary POJO's... then  why keep calling it EJB? The "enterprise" is slowly being removed from the equation. No container is required to use JPA, and no server is needed for session beans because you can run the container outside an app server. It still screams POJO, POJO, POJO to me. Then I'd rather use a POJO approach bottom up.

Yes, Spring is a container, but I *instantiate* and control the container. I don't control the container in most app servers. Perhaps I should have said "in a container controlled by a server".

David Sills replied on Mon, 2008/06/16 - 5:07am

One question: EJBs are fine (I'm liking 3.0 as well, and for most of the reasons mentioned). However, there's one point I don't understand in most discussions of EJB 3.0. People talk about how annotations replace XML files, and for the most part, that's true. However, when you have an enterprise app, typically there are at least three environments into which the app must be deployed: development, test, and production. No guarantees can be given (at least in most places I have worked) that the schema names will be the same in all three. How do folks get around having an orm.xml file in this kind of situation?

 

John Ferguson Smart replied on Mon, 2008/06/16 - 5:51am

Nice post. I admit that EJB 3 has made huge progress since the bad old days of EJB 2.x. And the competition between EJB 3 and Spring/Hibernate is IMO very healthy for the industry as a whole. Annotations in Spring 3.x have similarly made Spring a whole lot nicer to use than with a whole lot of cumbersome XML configuration files. However, in a Spring 3 application, I can write both unit (tests in isolation, possibly using mocks) and integration (classes deployed in the Spring context (or "container", if you prefer) tests directly in JUnit, without having to deploy anything anywhere. This has always been one of my biggest issues with EJBs. How possible will this be in EJB 3.1?

adam bien replied on Mon, 2008/06/16 - 8:05am in response to: John Ferguson Smart

Hi John,

 it is absolutely possible. In my projects, I'm going the pragmatic way, and instantiate the EJBs with JPA directly in the Unit Test. Bootstrapping of JPA takes about 2 lines of code (actually - great idea for the next post), you will need for every additional dependency one line of code. In general you will not get to many dependencies (1-5) between EJBs so it's o.k.

However you can use JBoss Embedded Container, Spring's Pitchfork or Glassfish v3 (soon) for this purpose.

 EJB 3.1 are embeddable / embedded per default - so this issue is fully solved. And remember, this without XML :-)!

adam bien replied on Mon, 2008/06/16 - 9:12am in response to: PJ Murray

You can deploy Session Beans with any granularity you like. From coarse grained, even message like interfaces, to very fine grained, domain driven (object oriented) local gateways. Remote interfaces are coarser in general, than the local one.

The granularity of a Session Bean is comparable with a Java interface - I cannot see any limitation. Do you probably mean CMP 1.0 Beans? Then you are right, but this technology is dead since 1960' :-)

Fabrizio Giudici replied on Tue, 2008/06/17 - 8:33am

As time passes, I really can't find the right words to participate in these discussions: the point is that EJB and Spring are getting closer and closer (both are POJOs, both need a container, both can be used with configuration files or annotations), so today choosing one over the other seems to be mostly a matter of personal taste. This of course means that Adam is right and EJB 3 are good. Until a few time ago, I supposed there was a major difference: with EJB you can do things only in one way, and you get all the services or none in a monolithic fashion, while with Spring you can only ask for a single service, e.g. only transaction management, and you can control things at fine grain (e.g. choose your transactional manager, etc...). One of the things I've most appreciated about Spring is the capability of decorating existing beans to fit your needs. But, AFAIU, Glassfish 3 with its modular structure is going to offer more or less the same thing - am I right?

At the moment I'm going to introduce one of the two technologies in my Rich Client Platform application. My original idea was, and still is, about Spring; but I must confess that Adam is making me think more and more about EJBs... :-) 

Andy Gibson replied on Tue, 2008/06/17 - 11:02am

As someone has already stated, Spring is a container, a proprietary one at that, and you still have to lug it around and initialize it in all your applications whether on the server, desktop, or in testing. Now initializing the Spring container is relatively simple, but there are embedded EJB implementations (albeit probably more complex) that you can use for testing.

Also, the one thing not really mentioned here is that EJB lets you have state on the server side. Yes, there is the Session, but that is fraught with dangers when you take replication, the lack of dirty checking and the issue of immutable versus mutable objects. There is the option of writing to the DB, but can soon become a bottleneck. Yes, you can throw a cache in there, but then you end up with having state on the server which is the same thing that was objected to with EJBs.

Spring pushed for a stateless architecture for years, and then ajax came along and the need for stateful bean management and they are introducing the concept of state with Spring Web Flow. If you are writing an online store and can put everything in a session scoped shopping cart and user account, then great, but most applications run a little more complex than that.

I've seen plenty of hacks and bad solutions to the state management problem, and people seem to shun a real solution to the problem because of 'overhead' which they fear like they have to give a pint of blood for every extra few meg of 'overhead' that is sitting there doing nothing.

Fabrizio is right though, the two are merging so close it is almost a pointless debate. The EJB servers are becoming more modular and giving you the option to only include services that you need. Furthermore, if it becomes a Web Beans world, then it will no longer be a question of whether you use Spring or EJB. It will be a question of whether you use an EJB or Spring (or other) implementation of Web Beans. Which raises the question of what that means for Spring long term in a Web Beans world when developers no longer use the proprietary Spring syntax and opt for the standard Web Beans syntax.

As an aside, the one thing I do like about Spring is the transparency of the setup. I deploy to an EJB container and "somehow" my calls are wrapped in transactions. With Spring I set up a transaction manager and apply transactions to calls using AOP. Spring does give you a feeling of being more in control at the expense of having to set everything up yourself. Might be nice to have an EJB server which is as transparent in terms of the implementation of its services (I'm no expert, so there may well already be one!)

Fabrizio Giudici replied on Tue, 2008/06/17 - 12:46pm

Spring does give you a feeling of being more in control at the expense of having to set everything up yourself. 

I agree on that too. But, for instance, I have seen people to whom I've presented both technologies and were much more attracted by EJBs (in spite of my light/medium Spring bias) where "things just work" and you don't have to set up a handful of beans for the TX manager etc... Which is not an argument to me, I mean the thing is apparently more complex, but once you learn it you make it work forever, but everybody has his own perspective on this.

George Jiang replied on Tue, 2008/06/17 - 7:01pm in response to: Jakob Jenkov

[quote=jj83777]

It seems a lot of things are "fixed" in EJB 3.1. But still, to me it seems like EJB is moving towards ordinary POJO's... then  why keep calling it EJB? 

[/quote]

 Isn't it emperor's cloth?

Andy Gibson replied on Tue, 2008/06/17 - 10:08pm in response to: George Jiang

The fact that they are written as POJO's doesn't invalidate the fact that on the server, they are still EJBs. They exhibit the same characteristics and can be used in the same way that EJBs have always been used.

 One could just as easily ask why they are called Spring Beans when they are POJOs.

 

Andy Gibson replied on Tue, 2008/06/17 - 10:16pm in response to: Fabrizio Giudici

[quote=fabriziogiudici]

I agree on that too. But, for instance, I have seen people to whom I've presented both technologies and were much more attracted by EJBs (in spite of my light/medium Spring bias) where "things just work" and you don't have to set up a handful of beans for the TX manager etc... Which is not an argument to me, I mean the thing is apparently more complex, but once you learn it you make it work forever, but everybody has his own perspective on this.

[/quote]

You know that is a good point. I remember looking at the Spring MVC step by step tutorial. The first few installments were all XML and setting up the environment! It can be somewhat daunting at first but step by step you can get there. I guess developers like quick results, but many developers should, after time, start to wonder how things work under the hood, and with Spring, things are a little more obvious and don't include a huge 'black box' container. Even the spring container is simple to comprehend and it seems quite obvious how the Bean factory might work based on the XML you write.

Also, as an unrelated point, the other thing I don't like about EJB is that it isn't at all simple to use your EJBs in desktop apps unlike Spring Beans.

Ryan Developer replied on Tue, 2008/06/17 - 10:44pm in response to: Andy Gibson

[quote=Andy Gibson]Also, as an unrelated point, the other thing I don't like about EJB is that it isn't at all simple to use your EJBs in desktop apps unlike Spring Beans.[/quote]

Isn't it as simple as adding the OpenEJB jar to your desktop project?  If you want transactions, add JTA to the mix?  Same as Spring, but I don't think many people do that.  I would show you the link to OpenEJB's examples where it is embedded in unit tests and desktop apps, but the last two times I posted a comment on here linking to EJB unit testing information the moderator didn't let it through.  Not sure why. 

WebBeans will have more sophisticated DI and works nicely with EJB 3.1, but WebBeans was designed for server use.  I don't like that they put Web in the name since DI is useful for other things too.  I don't think the JSR is considering use in Java SE for 1.0. 

Ryan Developer replied on Tue, 2008/06/17 - 10:53pm

It seems that whenever I paste a link in a comment it gets flagged for moderation.  I've been trying to answer questions about unit testing EJBs.  I will try to answer without posting links.  You have a couple options options:

1) Use ejb3unit to help mock objects.

2) Embed the OpenEJB container in your unit tests like you can do with Spring. 

Fabrizio Giudici replied on Wed, 2008/06/18 - 12:58am

Yes, I don't think EJB are so hard to integrate in a desktop application. Adam told me that even the Glassfish approach is feasible.

Andy Gibson replied on Wed, 2008/06/18 - 9:12am

I was going from my Seam experiences and reading on the forums posts from users who were trying to use the embedded JBoss container in Tomcat to run EJB Seam applications. It seemed rather complex at the time and people were running into problems.

You could be right in that it just takes adding OpenEJB to the project to test the EJBs, I haven't really looked at it closely to be honest, but that is good news.

Cheers,

 Andy Gibson 

 

 

Comment viewing options

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