Calling EJB 3 Session Beans from Spring

There’s been quite a bit of discussion these days as to which technology is best for developing enterprise applications – EJB 3 or Spring?  In my view it’s not an “either-or” question, both technologies have their strong points and use within an application.  When deciding which technology to use, my answer is “simplicity wins”.  Given a particular component to implement the best technology is the one that 1) accomplishes the goal, 2) minimizes complexity, and 3) is the quickest to implement with the least amount of code.

With the release of the EJB 3 specification writing applications using EJB is a much easier process.  By using EJB annotations we no longer have to write tedious XML deployment descriptors.  A simple POJO can be turned into a local stateless session bean with as little as two annotations, three if remote session beans are also needed.  Given the ease by which we can now write stateless session beans we prefer EJB 3 as the technology of choice for implementing an application’s business layer and Spring MVC for implementing the application’s front-end GUI.

Integrating a Spring MVC GUI with a back-end EJB business layer is fairly simple.  All we have to do is add bean definitions representing the various EJB session beans to Spring’s applicationContext.xml file.  The Spring MVC code then interacts with the session beans in the same way as with other Spring-managed beans.  The following code snippet illustrates the installation of a local session bean as a Spring-managed bean:

<jee:local-slsb id="ServiceTopic" jndi-name="java:app/business-0.1.0/ServiceTopic!com.snlb.debate.business.api.ServiceTopicLocal" business-interface="com.snlb.debate.business.api.ServiceTopicLocal" />

Note that we use portable JNDI names to reference the EJB session beans.  JEE 6 standardizes JNDI names at global, application, and module levels.  EJBs deployed to EJB 3.1-capable servers such as Glassfish will have various standard JNDI names registered.  The EJB 3.1 spec defines the following 3 levels of EJB JNDI names:

  • Global scope:  java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
  • Application scope: java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
  • Module scope: java:module/<bean-name>[!<fully-qualified-interface-name>]

In our application the Spring MVC GUI layer resides within the same EAR as the EJB business layer.  Thus we can reference the session bean using the application-scoped JNDI name.  We also have to include the fully qualified local interface name to instruct Spring to reference the session bean using the local session bean interface.

Leave a Reply

Your email address will not be published. Required fields are marked *