Welcome!

Java Authors: Miko Matsumura, John Ryan, Loraine Antrim, Walter H. Pinson, III, Jason Dolinger

Related Topics: Java, Websphere

Java: Article

Spring and EJB 3.0 in Harmony

In search of the best of both worlds

As you could see throughout the code, a lot of methods are described as JMX-managed. You've probably heard what the JBoss AS microkernel is all about. It's a JMX server. So what else would you expect; the deployers are also JMX MBeans. Each MBean, or call it service, must have its descriptor file. In JBoss that file is META-INF/jboss-service.xml:

<server>
   <mbean code="org.jboss.spring.deployment.SpringBeanFactoryDeployer"
name="jboss.spring:service=SpringBeanFactoryDeployer" />
</server>

Or you can use the whole power of Spring's application context (postprocessors, message source, event multicaster, listeners, ...) class by changing the content of our jboss-service.xml file to:

<server>
   <mbean code="org.jboss.spring.deployment.SpringApplicationContextDeployer"
name="jboss.spring:service=SpringApplicationContextDeployer" />
</server>

So now our Spring Deployer is coded up and we have to package it. JBoss provides a .deployer archive type. When you put this archive type in the JBoss deploy directory, JBoss will automatically be able to use the new archive type you've defined in your new deployer. Our Spring deployer archive structure looks like this:

jboss-spring-jdk5.deployer/
    jboss-spring-jdk5.jar
    spring-beans.jar
    spring-context.jar
    spring-core.jar
    META-INF/
      jboss-service.xml

Injecting Spring into EJBs
So now we have a way to package Spring and get it into the JBoss environment. It's time to write the "glue" that injects Spring beans into an EJB. The idea would be to define a new annotation to do this:

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Spring {
      String jndiName();
      String bean();
}

The annotation would be used inside an EJB this way:

@Stateless
public class MyBean implements MyRemote {

    @Spring(jndiName="myApp", bean="SomeBean")
    private SomeBeanClass pojo;

}

So how do we get the JBoss EJB 3.0 container to understand the @Spring annotation and do the injection for us? The answer is JBoss AOP. How to write such an aspect? Let's walk through it step-by-step.

The first thing to do is write an interceptor that has all of our Spring injection logic. Let's look at the implementation in Listing 4.

This interceptor will intercept the construction of the EJB. The inject() method is responsible for getting the class of the object and reflecting on it to find the setter methods and/or fields that have the @Spring annotation attached to it. From the information in the @Spring annotation, the interceptor looks up the bean factory in JNDI and injects the bean into the annotated method or field. I won't go into the boring details of the inject() method, but do note that it's encapsulated in the SpringInjectionSupport base class. Later in this article, I'll show you a more portable way of defining this Spring injection annotation so that it can be used in other EJB 3.0 containers as well as in JBoss.

So now that the interceptor is defined, we need a way to bind it into the EJB environment. To do this, you need to edit the ejb3-interceptors-aop.xml file in the JBoss deploy directory. This file contains all defined interceptor and interceptors bindings used by all the EJB containers. We'll have to add a declaration of our Spring interceptor there:

<interceptor
class="org.jboss.spring.interceptor.SpringInjectionInterceptor"/>

Next we have to bind this interceptor to each EJB container definition. If you look at the ejb3-interceptors-aop.xml file you'll see a bunch of AOP domains defined for each container type. You'll have to add the following to each domain:

<bind pointcut="execution(*->new(..))">
   <interceptor-ref name="org.jboss.spring.interceptor.SpringInjectionInterceptor"/>
</bind>

The SpringInjectionInterceptor will now be invoked every time an instance of an EJB is created. But what if the @Spring annotation isn't used? Isn't this interceptor additional overhead? JBoss AOP has ways of defining a more complex pointcut expression to avoid applying the interceptor, but I won't get into the details here. Check out the JBoss AOP documentation for more details.

An interesting thing about this interceptor and XML bindings is that they can be reused outside of EJB 3.0. If you use a full JBoss AOP, you can use the @Spring annotation to inject Spring-defined beans into any plain Java Class. You're not limited to using this annotation to EJBs.

That's it! We've integrated JBoss, Spring, and JBoss EJB 3.0.

Portability with EJB 3.0 Interceptors
One problem with using the JBoss AOP approach to integrating EJB 3.0 and Spring is that you have to use JBoss AOP. Sure JBoss AOP is usable outside of the JBoss application server, but do I really want a full-blown AOP implementation just to enable injection into my EJBs? Luckily, the EJB 3.0 specification provides a way to do this portably in any vendor's EJB 3.0 implementation.

EJB 3.0 has the concept of interceptors. Not only can you intercept methods, but you can also intercept EJB callback events like @PostConstruct (ejbCreate for you EJB 2.1 users). To intercept callbacks, you have to write something called an Interceptor. The Interceptor is a plain Java class with methods annotated with the callback event you're interested in intercepting. These methods take one parameter, the bean instance whose callback you are intercepting. What we can do is write one of these interceptors to do the same kind of injection processing we did with a JBoss AOP interceptor:

public class SpringLifecycleInterceptor extends SpringPassivationInterceptor {

    @PostConstruct
    public void postConstruct(Object bean) throws Throwable {
      inject(bean);
    }

}

We can apply this interceptor using an annotation on the bean class:

@Stateless
@Interceptors(value = SpringLifecycleInterceptor.class)
public class MyBean ... {
...
}

Alternatively, a partial XML deployment descriptor can be used to apply the callback:

<interceptor-binding>
    <ejb-name>MyBean</ejb-name>
    <interceptor-class>
org.jboss.spring.SpringLifecycleInterceptor
    </interceptor-class>
</interceptor-binding>

It would be quite annoying to have to apply this interceptor to each and every bean class or define it for each bean in XML, so there in the final draft of the EJB 3.0 specification will be a way to define default interceptors.

Conclusion
JBoss Deployers lets me create a new Spring archive type that's hot-deployable as-is into the JBoss runtime. That in and of itself is a simple, but powerful way to bootstrap Spring into the JBoss environment without having to write any of the specific bootstrap code that you normally have to write when using Spring.

EJB 3.0 greatly simplifies the development of enterprise applications. Annotations make it very easy to define and deploy EJBs without having to use XML. EJB 3.0 has some dependency injection, but it's not complete. Spring can be used as a compliment to EJB 3.0 to fill in the dependency injection gaps in the Java EE specification. With JBoss AOP or interceptors, I could easily define a new @Spring injection annotation to inject these deployed Spring beans directly into an EJB.

Resources
The JBoss Spring Deployer and EJB 3.0 integration is a free download:
http://sourceforge.net/project/showfiles.php?group_id=22866&package_id=161914

JBoss has also created a new Spring Integration forum where you can talk about other ways you'd like Spring to be integrated into the JBoss environment:
www.jboss.org/index.html?module=bb&op=viewforum&f=223

About Ales Justin

Ales Justin is a Java developer at Genera Lynx d.o.o. He's also a JBoss contributor and committer.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
SYS-CON Italy News Desk 02/27/06 03:00:53 PM EST

The new EJB 3.0 specification supports some notion of dependency injection via annotations. As an avid Spring user, I'm used to configuring fine-grained beans with Spring bean factories and XML. How does EJB 3.0 compare? More importantly, can we use EJB 3.0 POJOs and Spring POJOs side-by-side in applications? In this article, I'll try to answer those questions based on my own investigations and experiences. As it turns out, using a versatile application server like the JBoss Application Server (AS), Spring and EJB 3.0 POJOs can co-exist in harmony in your applications.