Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT, IBM Cloud

Java IoT: 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:

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

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:

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

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:


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})
public @interface Spring {
      String jndiName();
      String bean();

The annotation would be used inside an EJB this way:

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:


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"/>

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 {

    public void postConstruct(Object bean) throws Throwable {


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

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

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


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.

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.

The JBoss Spring Deployer and EJB 3.0 integration is a free download:

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:

More Stories By Ales Justin

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

Comments (1)

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.

IoT & Smart Cities Stories
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...