Spring: Creating Objects So You Don't Have To
ne of the more exciting open-source Java frameworks that has gathered steam in the last year is Spring. Spring aims to minimize dependency of application components by providing a plug-in architecture. Because Spring links objects together instead of the objects linking themselves together, it is categorized as a 'dependency injection' or 'inversion of control' framework.
Spring's object linking is defined in XML files, thus you can plug-in different components during runtime, or for different application configurations. This is particularly useful for applications that do unit testing or applications that deploy different configurations for different customers.
There are three primary types of dependency injection: setter-based, constructor-based, and interface-based injection. Spring supports both setter-based and constructor-based injection. As you will see later, this means Spring is able to create an object by passing objects references to its constructor and can modify the state of the object by calling its setter methods.
The terms 'dependency injection' and 'inversion of control' are often used interchangeably. Martin Fowler recently elaborated on the terminology, stating that dependency injection is a specific type of inversion of control. Specifically, dependency injection is a pattern where the responsibility for object creation and object linking is removed from the objects themselves and moved into a factory. Thus, dependency injection inverts the control for object creation and linking.
Though dependency injection is the basis of the Spring framework, Spring also provides a rich set of tools built on top of its core dependency injection functionality. Spring provides an MVC framework, support for several presentation frameworks, a transaction management framework, DAO support, support for several O/R mapping tools, and more.
This article is the first in a two-part series. I will introduce you to Spring's basic dependency injection functionality and its JDBC toolkit. In the next article, I will introduce you to several other Spring features by building a simple Web-application using Spring's MVC framework.
Injecting Dependency Using Factories
In this section I'll show you an example of a class that you might want to refactor in order to use dependency injection. First, you'll refactor the class programmatically, so that you can see how the pattern works without the use of a dependency injection framework. After that, you'll explore how to inject dependencies using Spring.
The following example demonstrates a tight coupling between two classes (the DataProcessor class and the FileDataReader class).
class DataProcessor public Result processData() { FileDataReader dataReader = new FileDataReader("file1.data"); Data data = dataReader.readData(); return data.calculateResult(); } client code DataProcessor fileDataProcessor = new DataProcessor(); Result result = fileDataProcessor.processData(); DataProcessor depends explicitly on FileDataReader. If we wanted to process data from another source (say a database) we would have to refactor the existing DataProcessor to operate on a more generic DataReader interface. One way to decouple the two is to push the creational responsibility for the DataReader out to the client code.
Here is the code, after refactoring:
class DataProcessor private DataReader dataReader; public DataProcessor(DataReader reader) { this.dataReader = reader; } public Result processData() { Data data = dataReader.readData(); return data.calculateResult(); } interface DataReader public Data readData(); client code FileDataReader dataReader = new FileDataReader("file1.data"); DataProcessor fileDataProcessor = new DataProcessor(dataReader); Result result = fileDataProcessor.processData(); Notice that the DataProcessor class no longer operates on FileDataReader, but rather on the DataReader interface that FileDataReader implements. By generalizing the interface, we've made DataProcessor more generic and reusable. The problem now is that any client code that wants to process data in a file has to create and link all the objects itself. Instead, we could inject the dependency between the DataProcessor and the DataReader using one or more factory classes.
One way would be as follows:
class DataProcessorFactory public static DataProcessor getFileDataProcessor() { DataReader reader = new FileDataReader("file1.data");; DataProcessor dataProcessor = new DataProcessor(reader); return dataProcessor; } client code DataProcessor fileDataProcessor = DataProcessorFactory.getFileDataProcessor(); Result result = fileDataProcessor.processData(); The DataProcessorFactory class is now responsible for creating and assembling our objects, and thus we have inverted control by way of dependency injection.
This Week's Multicore Reading List
MATLAB and Google App Engine
Logging In C++ : Part 2
Improving log granularityA Conversation with BitMagic's Developer
Prefer Structured Lifetimes: Local, Nested, Bounded, Deterministic
- Intel Parallel Studio; Download the free eval today!
- Parallelism Breakthrough Video Series; Watch and learn more about Intel® Parallel Studio
- 2009 Intel Software Webinar Series; View On-Demand webinars
- Coding for Multi-core Processes; Intel® Compiler Pro eBook
- Performance Through Parallelism; Intel® Tuning for Vista eBook
- Intel® Software Network; Connect with developers and Intel engineers
-
November 17, 2009
Visual Effects for Animation - presented by DreamWorks Animation
Speaker: Ron Henderson (Bio)Ron Henderson manages the FX Tools group at DreamWorks Animation, where he is responsible for developing physical simulation and procedural modeling tools. These systems have been used for key visual effects in recent films such as Kung Fu Panda and Monsters vs. Aliens (March 2009).
Prior to joining DreamWorks in 2002 he was a senior scientist at Caltech with a joint appointment to the Applied Math and Aeronautics departments, where he worked on efficient techniques for the direct numerical simulation of fluid turbulence.Abstract:
In this webinar, Ron Henderson will show examples of visual effects, from hair and feathers to smoke and fire, from a variety of DreamWorks Animation feature films. He will discuss in general terms the kinds of techniques used to achieve particular visual effects. Finally, Henderson will show a detailed breakdown of the dam-breaking scene from Madagascar: Escape 2 Africa, demonstrating how different elements of key frame animation, simulation, and rendering are combined in a real production shot. -
December 1, 2009
A Quick and Easy Way to Parallelize a Legacy Codebase with Intel® Threading Building Blocks (TBBs)
Speaker: Bernard Laberge, Avid, Senior Principal Engineer (Bio)Bernard Laberge is a senior principal engineer in the video editors division at Avid. During his seven years with the company he has been actively involved in the replacement of the legacy video processing engines used by Avid editors with a common hardware-abstracted, component-based video processing engine currently running on the CPU with SIMD optimized code, GPU, and dedicated hardware.
Abstract:
Learn how to overcome the limitations of a thread-based scheduler, including dealing with the absence of recursive parallelism support and the inefficient handling of unbalanced processing load. Bernard Laberge addresses how Avid resolved the expensive refactoring of their thread-based scheduler into a task-based solution by choosing Intel® Threading Building Blocks (TBBs). He explores how Avid was able to easily integrate the Intel TBBs into their video editor applications and more than 5 million lines of code. -
December 15, 2009
How to Use Intel® Parallel Studio to Streamline Code Development in a Multicore Environment
Speaker: Matt Dunbar, Director for Performance Technology, SIMULIA (Bio)Matt Dunbar is the director for performance technology at SIMULIA. Since joining the company in 1993, he has worked on parallelization of the Abaqus suite of products, initially for shared memory architectures and more recently for distributed memory architectures. Dunbar has also been intimately involved in selecting both the hardware and software tools used in the development of the Abaqus product line.
Abstract:
Resolve elusive, costly multithreading errors quickly and efficiently with Intel® Parallel Studio. While many coding problems that lead to bugs in software applications are typically straightforward logic errors, errors in managing memory and in multithreading code can sometimes take weeks to months to diagnose and fix. Matt Dunbar explores how and why taking advantage of multicore processors through multithreaded code is critical for compute-intensive applications. While spotlighting his work on SIMULIA's Abaqus finite element solver, Dunbar addresses the need for multicore execution and shares his experiences using Intel Parallel Studio to streamline code development in a multicore environment.



