Welcome!

Java IoT Authors: Liz McMillan, Jason Bloomberg, Zakia Bouachraoui, Elizabeth White, Yeshim Deniz

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:

<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

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
Here are the Top 20 Twitter Influencers of the month as determined by the Kcore algorithm, in a range of current topics of interest from #IoT to #DeepLearning. To run a real-time search of a given term in our website and see the current top influencers, click on the topic name. Among the top 20 IoT influencers, ThingsEXPO ranked #14 and CloudEXPO ranked #17.
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...
According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
Contextual Analytics of various threat data provides a deeper understanding of a given threat and enables identification of unknown threat vectors. In his session at @ThingsExpo, David Dufour, Head of Security Architecture, IoT, Webroot, Inc., discussed how through the use of Big Data analytics and deep data correlation across different threat types, it is possible to gain a better understanding of where, how and to what level of danger a malicious actor poses to an organization, and to determin...
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
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.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
Rafay enables developers to automate the distribution, operations, cross-region scaling and lifecycle management of containerized microservices across public and private clouds, and service provider networks. Rafay's platform is built around foundational elements that together deliver an optimal abstraction layer across disparate infrastructure, making it easy for developers to scale and operate applications across any number of locations or regions. Consumed as a service, Rafay's platform elimi...
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...