Click here to close now.


Java IoT Authors: Elizabeth White, Pat Romanski, Flint Brenton, Liz McMillan, Jennifer Gill

Related Topics: Java IoT, Mobile IoT

Java IoT: Article

Java J2EE Lite with Spring Framework

The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning

J2EE applications of late have become weight conscious. The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning: technology driven design! Fortunately a host of lightweight solutions are emerging, such as PicoContainer, Spring Framework, Hivemind, Hibernate, Castor, and Webwork. In this article I'll discuss my experience with the Spring Framework and how it can be used to make a J2EE application more maintainable, testable, and better performing.

Although there are many areas that Spring 1.2.4 covers, I will be covering only Spring IoC (Inversion of Control) and Spring AOP (Aspect-Oriented Programming). These two along with the (non-Spring) concept of coding to interfaces form the cornerstone on which other Spring technologies are based.

Using Spring AOP and IoC we will see how you can replace container-provided infrastructure services for the following services, a la carte:

  • Logging
  • Transactions
  • Profiling
  • Auditing
  • Exception monitoring
We will also see:
  • Switching XA data sources for nonXA ones for certain methods
  • Accessing stateless session beans (SLSB) via a Spring application context
  • Accessing Spring application Contexts from a webapp
  • Integration tests using IoC and JUnit
  • Unit testing using EasyMock and JUnit
To demonstrate these services we will be using a simple ordering application, made2order.

made2order Application
The made2order application showcases the above infrastructure services using the Spring Framework. Figure 1 shows the architecture of the application components.

The application consists of an OrderService interface implemented by the OrderServiceImpl concrete class. The OrderDAO interface is implemented by the JdbcOrderDAO concrete class. Finally the domain objects are represented by the Order and the LineItem classes. These six classes represent the POJO-based core business application (in magenta); the other classes are Spring classes (used for infrastructure functionality). JSP are used for presentation, packaged in the Web app, and there are two classes for testing

Database Design and Business Interface
made2order has a very simple database design shown in Figure 2.

The business interface for the made2order application is shown in Listing 1. The OrderServiceImpl class implements the above business methods. Note that the getDao() and setDao(...) methods are needed for "injecting" a dependent DAO (Data Access Object Pattern) into the service (we will see more about this later) Patterns/DataAccessObject.html.

The implementation of these methods deals only with the business logic (and DAO interaction). It does not have knowledge of infrastructure services such as:

  • Transactions
  • Logging of enter/exiting from methods
  • Auditing
  • Profiling long-running methods
  • Reporting when exceptions occur
  • Data source switching
We will see how the above services will be applied to the made2order application in a non-invasive manner.

Using made2order
The accompanying application is meant to serve as an example for the Spring technologies discussed in this article. The downloadable bundle at Listing 1 is a zip file that can be imported into the Eclipse IDE as an Eclipse project.

You can do either one of the following actions (or both) as you read through this article:

  • Go through the source code using your favorite IDE and run JUnit tests to understand the examples. The JUnit test suite file ( in the test folder contains several methods to test the above services.
  • Install the Web app in a J2EE application server (does not need EJB support) and navigate through the Web pages with the examples.
We will start with the Spring BeanFactory.

Spring Bean Factory and IoC
The Spring BeanFactory represents a class that manages the life cycle of singleton services (among other things). These services are injected with dependencies using Inversion of Control ( Services that depend on external resources are "told" what those dependencies are instead of "getting" them using the Service Locator pattern ( Patterns/ServiceLocator.html).

The injection of dependents is achieved either via a constructor or setter injection. The JavaBean that represents the service has a "set" method that accepts the dependant (setter injection) or it has a constructor that accepts the dependent object (constructor injection). Using an XML configuration file, the service object is configured with its dependent objects using either of these two mechanisms. (The XML file is just one of many formats the configuration can be specified in, others being properties files or just plain Java code.)

There can be one or more bean factories in an application. Bean factories can be overlaid, such that there is one for production but it's overlaid by the one for development.

The bean factory is accessed by the presentation layer to access services offered by the application. In made2order, the OrderService service is needed as a singleton. The OrderService implementation is dependent on an implementation of OrderDAO. The OrderDAO implementation in turn is dependent on JdbcTemplate object, (a Spring-supplied helper class that helps with JDBC operations). The JdbcTemplate requires an implementation of a data source. In this case, myDataSource is a data source implementation that is specified in the BeanFactory and injected into the JdbcTemplate.

The BeanFactory returns a singleton of OrderService after "injecting" required dependencies in it as shown in the Figure 3.

Note that an implementation is injected into an interface at each level.

Figure 3 is represented in the XML file orderContext.xml shown in Listing 2. In this listing we see that the BeanFactory defines two data sources. During configuration, either of the data sources is injected into the JdbcTemplate instance.

Spring Proxies
In the general sense of the word, a proxy is a class that sits between the business class and the client. In the context of Spring, however, a proxy is either a JSE dynamic proxy or a static proxy that implements infrastructure services and is "injected" with a dependency that is the target business class. Then, instead of the client being given a reference to the target service, it's given a reference to the proxy. In this manner the behavior implemented in the proxy is interjected into the service seen in Figure 4.

With the current release, Spring proxies allow interception at the method level only, whereas some full-blown AOP environments allow field-level interception also. Proxies can be dynamic (JSE dynamic proxies), in which case Java interfaces are proxied; or they can be static, in which case bytecode modification occurs. Understandably, static proxies outperform dynamic ones but only marginally.

Interception is implemented using concepts from AOP: pointcuts and advice.

Pointcuts and Advice
Advice classes specify the actual work to do upon interception whereas pointcuts tell Spring where to apply advice.

The combination of a pointcut and an advice is bundled in what Spring calls an Advisor (see Figure 5).

We will see Advice, Advisors, and Pointcut classes in action in a made2order application when we apply infrastructure services to the business classes.

The following sections explain how each infrastructure service has been implemented.

Transaction Service
The OrderService's placeOrder(...), modifyOrder(...), and dropOrder() methods need to be transaction-bound. For this we modify the orderContext.xml file by configuring a Spring-supplied transactional proxy called TransactionProxyFactoryBean. As shown in the Listing 3, an instance of this proxy is called myProxiedServiceWithSeveralInterceptors.

The TransactionAttributes section is supplied with regular expressions that represent the methods that need to be transaction bound (PROPAGATION_REQUIRED) and those that are not (PROPAGATION_SUPPORTS).

Also, the target of this proxy is specified as orderService, which is the instance of the OrderServiceImpl.

Note that a transactionManager is injected into the proxy. An instance of transactionManager is set up elsewhere in the configuration file.

The preInterceptors are a list of Advices and/or Advisors that are also tacked onto this proxy in what is called a chain of interceptors. We will see each of these in turn later. For now, note that preInterceptors are invoked before the target is invoked in the order specified.

Seeing Transactions in Action Using JUnit
For testing transactions there are two test methods in the test suite: testNonProxiedServiceForModifyingAnOrder() and testProxiedServiceForModifyingAnOrder(). Both these methods call the modifyOrder(...) method on the non-proxied service in one case and proxied service in the other. The modifyOrder(...) method updates the ORDER_TABLE table first and then each lineItem in the ITEM_TABLE. The test method updates an order with two line items. The second lineItem has a description whose length is greater than the column width in the database. This forces an error upon update of the line item description in the database. Both the test methods update the ORDER_TABLE first and then the first lineItem in the LINE_ITEM table before throwing an exception while trying to update the long description in the second line item. The proxied method issues a rollback whereas the non-proxied method commits the update to the ORDER_TABLE and the first lineItem in the ITEM_TABLE.

More Stories By Pankaj Tandon

Pankaj Tandon is a software engineer at Crowncastle. His interests include object-oriented design and development and architecting the software process using open source technologies. He is a Sun Certified Java developer for the Java 2 platform. He lives in Pittsburgh, PA, plays guitar, and mixes music in his spare time.

Comments (6) 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
Pankaj Tandon 02/21/06 10:38:18 AM EST

I just realized that if you are here then you have already found the online version of the article.. here is the link to the downloadable artifact then..

Click on "Additional Code II" to get the full webapp+ code.

Pankaj Tandon 02/17/06 05:48:23 PM EST

Hi all,
I have received several emails from folks telling me about this snafu on JDJs part.
The link is there burried somewhere in the JDJ labyrinth.
You can get to it and some performance analysis at:

Bob Raker 02/16/06 11:37:12 AM EST

This was a very good article. But, where the hell does one go to download listing 9-20. Thanks.

Rob Moore 02/14/06 12:14:11 PM EST

Is the sample code available?



SYS-CON Brazil News Desk 02/14/06 09:46:50 AM EST

J2EE applications of late have become weight conscious. The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning: technology driven design! Fortunately a host of lightweight solutions are emerging, such as PicoContainer, Spring Framework, Hivemind, Hibernate, Castor, and Webwork. In this article I'll discuss my experience with the Spring Framework and how it can be used to make a J2EE application more maintainable, testable, and better performing.

SYS-CON India News Desk 02/13/06 02:55:13 PM EST

J2EE applications of late have become weight conscious. The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning: technology driven design! Fortunately a host of lightweight solutions are emerging, such as PicoContainer, Spring Framework, Hivemind, Hibernate, Castor, and Webwork. In this article I'll discuss my experience with the Spring Framework and how it can be used to make a J2EE application more maintainable, testable, and better performing.

@ThingsExpo Stories
Continuous processes around the development and deployment of applications are both impacted by -- and a benefit to -- the Internet of Things trend. To help better understand the relationship between DevOps and a plethora of new end-devices and data please welcome Gary Gruver, consultant, author and a former IT executive who has led many large-scale IT transformation projects, and John Jeremiah, Technology Evangelist at Hewlett Packard Enterprise (HPE), on Twitter at @j_jeremiah. The discussion is moderated by me, Dana Gardner, Principal Analyst at Interarbor Solutions.
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
With all the incredible momentum behind the Internet of Things (IoT) industry, it is easy to forget that not a single CEO wakes up and wonders if “my IoT is broken.” What they wonder is if they are making the right decisions to do all they can to increase revenue, decrease costs, and improve customer experience – effectively the same challenges they have always had in growing their business. The exciting thing about the IoT industry is now these decisions can be better, faster, and smarter. Now all corporate assets – people, objects, and spaces – can share information about themselves and thei...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound effect on the world, and what should we expect to see over the next couple of years.
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the APIs that make today's multi-cloud environments and hybrid clouds possible. In this Power Panel at 17th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the importance of customers being able to use the specific technologies they need, through environments and ecosystems that expose their APIs to make true change and transformation possible.
The cloud. Like a comic book superhero, there seems to be no problem it can’t fix or cost it can’t slash. Yet making the transition is not always easy and production environments are still largely on premise. Taking some practical and sensible steps to reduce risk can also help provide a basis for a successful cloud transition. A plethora of surveys from the likes of IDG and Gartner show that more than 70 percent of enterprises have deployed at least one or more cloud application or workload. Yet a closer inspection at the data reveals less than half of these cloud projects involve production...
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" in this scenario: microservice A (releases daily) depends on a couple of additions to backend B (re...
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, wil...
PubNub has announced the release of BLOCKS, a set of customizable microservices that give developers a simple way to add code and deploy features for realtime apps.PubNub BLOCKS executes business logic directly on the data streaming through PubNub’s network without splitting it off to an intermediary server controlled by the customer. This revolutionary approach streamlines app development, reduces endpoint-to-endpoint latency, and allows apps to better leverage the enormous scalability of PubNub’s Data Stream Network.
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk was on IBM Cloudant, Apache CouchDB, and ...
Container technology is shaping the future of DevOps and it’s also changing the way organizations think about application development. With the rise of mobile applications in the enterprise, businesses are abandoning year-long development cycles and embracing technologies that enable rapid development and continuous deployment of apps. In his session at DevOps Summit, Kurt Collins, Developer Evangelist at, examined how Docker has evolved into a highly effective tool for application delivery by allowing increasingly popular Mobile Backend-as-a-Service (mBaaS) platforms to quickly crea...
I recently attended and was a speaker at the 4th International Internet of @ThingsExpo at the Santa Clara Convention Center. I also had the opportunity to attend this event last year and I wrote a blog from that show talking about how the “Enterprise Impact of IoT” was a key theme of last year’s show. I was curious to see if the same theme would still resonate 365 days later and what, if any, changes I would see in the content presented.
Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance across private and public clouds. Manual security compliance is slow, prone to human error, and represents over 50% of the cost of managing cloud applications. Determining how to automate cloud security compliance is critical to maintaining positive ROI. Raxak Protect is an automated security compliance SaaS platform and ma...
Internet of @ThingsExpo, taking place June 7-9, 2016 at Javits Center, New York City and Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 18th International @CloudExpo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo New York Call for Papers is now open.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York and Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th 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 cha...
We are rapidly moving to a brave new world of interconnected smart homes, cars, offices and factories known as the Internet of Things (IoT). Sensors and monitoring devices will touch every part of our lives. Let's take a closer look at the Internet of Things. The Internet of Things is a worldwide network of objects and devices connected to the Internet. They are electronics, sensors, software and more. These objects connect to the Internet and can be controlled remotely via apps and programs. Because they can be accessed via the Internet, these devices create a tremendous opportunity to inte...
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi’s VP Business Development and Engineering, explored the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context with p...
We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.