Welcome!

Java Authors: Pat Romanski, Liz McMillan, Elizabeth White, Trevor Parsons, Jason Bloomberg

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
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. 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 devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.