Dependency injection in Java

August 3, 2016

In this tutorial lesson, we will discuss one of the major concepts of Spring which is dependency injection. Before I explain to you what dependency injection is, let’s have a look on below example.

1. Tightly coupled classes example

Let’s create the class named SlowEngine with the method start. For the sake of this example, let’s make this method just print “Slow engine start” string:

And let’s assume that we have the class Car that uses this SlowEngine class. This class has also the method start that calls the SlowEngine.start() method.

And let’s construct the class CarExample which will just create the Car object and then call its start method.

As you can suppose the result of running the above class is like presented below:

But the class Car is highly dependent on the SlowEngine class because in the constructor of the class Car we create a new instance of the class SlowEngine. What if instead the SlowEngine class we just want to use another class like the FastEngine? Then we need to modify the class Car itself.

To avoid such a situation, we can use dependency injection. I will explain it to you by example.

2. Dependency injection example

2.1. Creating an interface and implementing it

So let’s create the interface Engine with the method start.

Then modify the class SlowEngine to implement the Engine interface, so it looks like this:

And now let’s create another class FastEngine that also implements the Engine interface:

As you can see these two methods differ only by the String they print.

2.2 Using an interface as a constructor parameter

But let’s now focus on dependency injection. As you remember in the first implementation of our Car class, we’ve created a new instance of the SlowEngine class in the constructor. To avoid this fact, we can inject an instance of an appropriate class as a parameter in the constructor. So let’ have a look on below example:

2.3 Testing dependency injection example

Now we can use whatever implementation of the Engine class we want. So let’s have a look at the class below:

As you can see in the method createAndStartCarWithFastEngine we create at first an instance of the SlowEngine class. And then we pass it in a constructor to the Car class. At the end, we call the method start of newly created Car instance. Similarly, we do in the second method. The result of calling the above main method will be:

As you can see in the second example, the Car class is now not dependent on any concrete implementation of the Engine interface. It’s only dependent on the Engine interface itself.

Spring framework has many features thanks to which we can make dependency injection much easier. I will cover this topic in the nest lesson of this tutorial.

Click here to add a comment

Leave a comment: