Welcome!

Java Authors: Torben Andersen, Elizabeth White, Liz McMillan, Patrick Carey, Adine Deford

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
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, 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...
"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.
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.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...

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...

SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
DevOps Summit 2015 New York, 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 widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @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 its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...