Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

Dependency Injection with the Spring Framework - Tutorial

Lars Vogel

Version 0.3

30.08.2009

Revision History
Revision 0.119.04.2008Lars Vogel
Described dependency injections
Revision 0.213.12.2008Lars Vogel
Added bean configuration based on annotations (for Spring 2.5)
Revision 0.330.08.2009Lars Vogel
fixed a few syntax errors

Spring dependency injection

This article describes how to use dependency injection with the Spring Framework.

It first describes dependency injection as a general principle, gives then an overview of Spring and explains then the configuration of Spring with annotations and with XML.


Table of Contents

1. Dependency Injection
2. Spring Overview
3. Spring Installation
4. Datamodel
5. Using dependency injection with annotations
6. Using dependency injection with XML
7. Summary
8. Thank you
9. Questions and Discussion
10. Links and Literature
10.1. Source Code
10.2. Spring Links

1. Dependency Injection

Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes(Unit Testing). To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather that the class itself creates / finds this object.

A class A has a dependency to class B if class uses class B as a variable.

If dependency injection is used then the class B is given to class A via

  • the constructor of the class A - this is then called construction injection

  • a setter - this is then called setter injection

The general concept between dependency injection is called Inversion of Control. A class should not configure itself but should be configured from outside.

A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access object) for receiving the data from a database you can easily create another test object which mocks the database connection and inject this object into A to test A without having an actual database connection.

A software design based on dependency injection is possible with standard Java.

Spring just add some simplifications in using dependency injection by providing a standard way of providing the configuration and by managing the reference to the created objects.