Click here to close now.

Welcome!

Java Authors: Plutora Blog, Harry Trott, Liz McMillan, Pat Romanski, Andreas Grabner

Related Topics: Java, Wireless

Java: 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) http://java.sun.com/blueprints/corej2eepatterns/ 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 (com.order.acme.OrderServiceIntegrationTest.java) 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 (www.martinfowler.com/articles/injection.html). Services that depend on external resources are "told" what those dependencies are instead of "getting" them using the Service Locator pattern (http://java.sun.com/blueprints/corej2eepatterns/ 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..
http://res.sys-con.com/story/feb06/180377/source.html

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:
http://technochord.blogspot.com/2006/02/j2ee-lite-with-spring-framework....

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?

Thanks,

Rob

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
Roberto Medrano, Executive Vice President at SOA Software, had reached 30,000 page views on his home page - http://RobertoMedrano.SYS-CON.com/ - on the SYS-CON family of online magazines, which includes Cloud Computing Journal, Internet of Things Journal, Big Data Journal, and SOA World Magazine. He is a recognized executive in the information technology fields of SOA, internet security, governance, and compliance. He has extensive experience with both start-ups and large companies, having been involved at the beginning of four IT industries: EDA, Open Systems, Computer Security and now SOA.
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
Operational Hadoop and the Lambda Architecture for Streaming Data Apache Hadoop is emerging as a distributed platform for handling large and fast incoming streams of data. Predictive maintenance, supply chain optimization, and Internet-of-Things analysis are examples where Hadoop provides the scalable storage, processing, and analytics platform to gain meaningful insights from granular data that is typically only valuable from a large-scale, aggregate view. One architecture useful for capturing and analyzing streaming data is the Lambda Architecture, representing a model of how to analyze rea...
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
SYS-CON Events announced today that Open Data Centers (ODC), a carrier-neutral colocation provider, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. Open Data Centers is a carrier-neutral data center operator in New Jersey and New York City offering alternative connectivity options for carriers, service providers and enterprise customers.
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
PubNub on Monday has announced that it is partnering with IBM to bring its sophisticated real-time data streaming and messaging capabilities to Bluemix, IBM’s cloud development platform. “Today’s app and connected devices require an always-on connection, but building a secure, scalable solution from the ground up is time consuming, resource intensive, and error-prone,” said Todd Greene, CEO of PubNub. “PubNub enables web, mobile and IoT developers building apps on IBM Bluemix to quickly add scalable realtime functionality with minimal effort and cost.”
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
With several hundred implementations of IoT-enabled solutions in the past 12 months alone, this session will focus on experience over the art of the possible. Many can only imagine the most advanced telematics platform ever deployed, supporting millions of customers, producing tens of thousands events or GBs per trip, and hundreds of TBs per month. With the ability to support a billion sensor events per second, over 30PB of warm data for analytics, and hundreds of PBs for an data analytics archive, in his session at @ThingsExpo, Jim Kaskade, Vice President and General Manager, Big Data & Ana...
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
The Internet of Things (IoT) is causing data centers to become radically decentralized and atomized within a new paradigm known as “fog computing.” To support IoT applications, such as connected cars and smart grids, data centers' core functions will be decentralized out to the network's edges and endpoints (aka “fogs”). As this trend takes hold, Big Data analytics platforms will focus on high-volume log analysis (aka “logs”) and rely heavily on cognitive-computing algorithms (aka “cogs”) to make sense of it all.
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
Since 2008 and for the first time in history, more than half of humans live in urban areas, urging cities to become “smart.” Today, cities can leverage the wide availability of smartphones combined with new technologies such as Beacons or NFC to connect their urban furniture and environment to create citizen-first services that improve transportation, way-finding and information delivery. In her session at @ThingsExpo, Laetitia Gazel-Anthoine, CEO of Connecthings, will focus on successful use cases.
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
The true value of the Internet of Things (IoT) lies not just in the data, but through the services that protect the data, perform the analysis and present findings in a usable way. With many IoT elements rooted in traditional IT components, Big Data and IoT isn’t just a play for enterprise. In fact, the IoT presents SMBs with the prospect of launching entirely new activities and exploring innovative areas. CompTIA research identifies several areas where IoT is expected to have the greatest impact.
Wearable devices have come of age. The primary applications of wearables so far have been "the Quantified Self" or the tracking of one's fitness and health status. We propose the evolution of wearables into social and emotional communication devices. Our BE(tm) sensor uses light to visualize the skin conductance response. Our sensors are very inexpensive and can be massively distributed to audiences or groups of any size, in order to gauge reactions to performances, video, or any kind of presentation. In her session at @ThingsExpo, Jocelyn Scheirer, CEO & Founder of Bionolux, will discuss ho...
SYS-CON Events announced today that GENBAND, a leading developer of real time communications software solutions, has been named “Silver Sponsor” of SYS-CON's WebRTC Summit, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. The GENBAND team will be on hand to demonstrate their newest product, Kandy. Kandy is a communications Platform-as-a-Service (PaaS) that enables companies to seamlessly integrate more human communications into their Web and mobile applications - creating more engaging experiences for their customers and boosting collaboration and productiv...
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, shared some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, a...