Spring Dependency Injection (DI)

In this tutorial you will learn about Spring Dependency Injection (DI) concept with example.

Dependency Injection is a design pattern that allows us to remove dependencies from code so that its easier to maintain and test the code.

Lets try to understand why we really need dependency injection.

Consider two classes Circle and DrawShape as given below.

In this example DrawShape class is dependent on Circle class because we have used new keyword to create Circle object. In case we change name of Circle class or its constructor arguments then we have to also do changes in DrawShape class as it uses Circle class.

Assume if the Circle class is used in 100 other classes. In that case we have to do changes in 100 classes and that will require lot of time and efforts. Also we can not test DrawShape class without importing Circle class.

So it becomes difficult to manage and test the code. To solve this problem Dependency Injection concept is used.

In Spring Framework there are two ways to inject dependency.

  • Dependency Injection Using Constructor (Constructor Injection)
  • Dependency Injection Using Setter Method (Setter Injection)

You can watch below video to understand Dependency Injection easily.

Spring Constructor Injection Example

Create a spring project with following files.

Shape.java

Circle.java

DrawShape.java

TestClass.java

configuration.xml

In above code I have used <constructor-arg> tag, it is used to inject Circle class object in DrawShape constructor at runtime.

Output

When you will run the project it will show following output in ide console.

Spring Dependency Injection (DI)

Spring Setter Method Injection Example

We simply replace constructor with setter method setShape() in DrawShape class.

Also replace <constructor-arg> tag with <property> tag in configuration.xml file.

The <property> tag inject the Circle object in setter method of DrawShape class at runtime.

All other code will be same as used in construction injection example.

Comment below in case you are facing any difficulty to understand Spring Dependency Injection concept.

1 thought on “Spring Dependency Injection (DI)”

Leave a Comment

Your email address will not be published. Required fields are marked *