Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Yeshim Deniz, Liz McMillan, Frank Lupo

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
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” 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. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
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...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, 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. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” 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. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...