Welcome!

Java IoT Authors: Pat Romanski, Stackify Blog, Elizabeth White, Liz McMillan, Mamoon Yunus

Related Topics: Java IoT

Java IoT: Article

Spring and Java EE 5 (PART 2)

Simplicity and power combined

Register for Real-World Java Seminar

In the first part of this article you learned how Java EE 5 has simplified enterprise application development by adopting a POJO programming model and making use of Java 5 metadata annotations. You also discovered how the Spring Framework version 2.0 integrates with Java Persistence API (JPA) and makes it simple to use from enterprise Java applications.

In this second part, you will learn how you can integrate the Spring Framework with EJB 3 components and to exploit Spring's declarative transaction features with Java EE applications. Finally we'll discover how Java EE application servers provide seamless management of Spring components from their JMX-enabled management consoles.

Using Spring and EJB 3
As we discussed in Part 1 of this article, EJB 3 greatly simplifies development of EJB components. Spring's Pitchfork project implements part of the EJB 3 specification, for example, enabling use of @Stateless or @Resource annotations with Spring beans. It also lets developers use @Stateless annotations in a web container.

You can mix and match EJB 3 and Spring components to leverage the power of both frameworks. For example, you can combine such features as statefulness, pooling, clustering, declarative security, Web Service feature, and message-driven beans of EJB 3 with AOP, POJO injection , template-based data, and resource access support provided by Spring.

Injecting Session Beans
You may remember from our earlier discussion that Java EE 5 lacks support for POJO injection. If you want to use an EJB from a helper class of your Web or EJB module then injection isn't supported and unfortunately you have to resort to JNDI lookup. Note that application server vendors will provide proprietary extensions to support POJO injection.

However you can use Spring to simplify and use its powerful dependency injection mechanism to inject an instance of a session bean. This will help your applications to port between application servers. Let us dive down and see an example.

The code examples that follow are taken from my recently published book, EJB 3 in Action, published by Manning Publications.

Assume that you have a session bean named ItemManager that you will use in the ItemServiceBean, which is a Spring POJO, as shown below:

public class ItemServiceBean implements ItemService {

private ItemManager itemManager;
public ItemServiceBean() {
}

// Setter injection of ItemManagerEJB
public void setItemManager(ItemManager itemManager) {
this.itemManager = itemManager;
}

public Long addItem(String title, String description,
Double initialPrice, String sellerId) {
Item item = itemManager.addItem(title, description,
initialPrice, sellerId);
return item.getItemId();
}
}

As you can see, we are using setter injection to inject an instance of ItemManager EJB object and invoke a method on the EJB.

By now you must be wondering where the actual magic happens? We're not doing a JNDI lookup and not using the @EJB injection (that we discussed in Part 1) to inject the session bean object. The real magic occurs through wiring in the EJB through the Spring configuration.

Let's assume that the Spring Bean uses a remote business interface of ItemManager EJB and retrieves it using a Spring 2.0 simplified jee-jndi lookup as follows:

<jee:jndi-lookup id = "itemManager" jndi-name = "ejb/ItemManager" resource-ref = "true"/>

Note that we are using setter injection in ItemServiceBean to inject an instance of ItemManager EJB and we must wire the ItemManager EJB as follows:

<bean id = "itemService" class = "actionbazaar.buslogic.ItemServiceBean">
<property name = "itemManager" ref = "itemManager"/>
</bean>

Remember from our discussion in part 1 of the article that EJB 3 Session beans are POJOs and interfaces are POJI. So there's no difference between invoking EJB3 session beans with either a remote or local interface if your Spring beans and EJBs are collocated in the same container, and the configuration is identical for both local and remote session beans. If your Session bean is in a remote container you'll have to provide the JNDI properties such has provider URL, principal, and credentials to invoke the remote bean.

Spring-Enabled Session beans
We 'll examine another interesting case of integration where you can leverage the power of Spring in an EJB 3-based application. You can use Spring in your session beans (both stateless and stateful) and message-driven beans (MDB). I'll demonstrate the use of Spring beans from an EJB 3 stateless session bean. If you've used Spring with EJB 2 you may remember that the framework provides several factory classes for such integration. You can use those abstract classes with EJB 3 session beans to enable access to the Spring bean factory. As these factory classes require they have to implement the onEjbCreate() method in your EJB 3 bean class to access a Spring bean.

Below is the same EJB 3 example (PlaceBid EJB) transformed into a Spring-enabled stateless session bean. Here the PlaceBid EJB acts as a façade and delegates the actual business logic to the PlaceBidServiceBean.

@Stateless(name = "PlaceBid")
public class PlaceBidBean extends AbstractStatelessSessionBean
implements PlaceBid {

private BidServiceBean bidService;
public PlaceBidBean() {
}

protected void onEjbCreate() {
bidService =
(BidServiceBean) getBeanFactory().getBean("bidService");
}

public Long addBid(String userId, Long itemId, Double bidPrice) {
return bidService.addBid(userId, itemId, bidPrice);
}
}

More Stories By Debu Panda

Debu Panda is a Director of Product Management at Oracle Corporation. He is lead author of the EJB 3 in Action (Manning Publications) and Middleware Management (Packt). He has more than 20 years of experience in the IT industry and has published numerous articles on enterprise Java technologies and has presented at many conferences. Debu maintains an active blog on enterprise Java at http://debupanda.blogspot.com.

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
jcl 11/24/09 01:16:00 PM EST

Hi,thank you for this tutorial

I'm interested on the first way to intregate Spring and EJB3.

I have tried it in a example project buy it doesn't run. I'm searching since many time a solution,but nothing.

I have posted on Spring forum,but no one seems can help me.

I appreciate if you can help me.Thank you

Antonio

@ThingsExpo Stories
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infrastructure throu...