Spring Dependency Injection & Inversion of Control

Kaushik Shaw
5 min readJun 13, 2021

--

As mention in the title today we are talking about spring IoC and DI. So before that, we have to know about Spring.

Spring: Spring is a framework. It provides a comprehensive programming and configuration model for modern Java-based enterprise applications. It focuses on the “plumbing” of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments. Spring normally helps developers to achieve loose coupling.

So there are two types of coupling one is tight coupling another is loose coupling.

Tight coupling: When two classes are highly dependent on each other, it is called tight coupling. It occurs when a class takes too many responsibilities or where a change in one class requires changes in the other class.

Loose coupling: loose coupling means they are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled.

Spring Inversion of Control: It is a principle in which transfers the control of objects to a container or framework. We most often use it in the context of object-oriented programming. In traditional programming, our custom code makes calls to a library, IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built-in. Responsible for object creation holds the object in memory. IOC creates the object of the class and provides that object wherever it is needed all this at runtime. It is basically responsible for maintaining an object’s life cycle.

Bean: The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that we supply to the container.

Example:

<bean id=”myCoach”

class=”com.spring.TrackCoach” >

</bean>

With the help of the bean id, we can call the methods in TrackCoach class.

Spring Dependency Injection: Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled. In this process, objects define their dependencies (that is, the other objects with which they work) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes or the Service Locator pattern.

Code is cleaner with the DI principle, and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies. As a result, our classes become easier to test, particularly when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.

So there are two types of DI :

  1. Constructor Injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class. The <constructor-arg> subelement of <bean> is used for constructor injection.

Example:

In .XML file:

<bean id=”myCoach”

class=”com.spring.TrackCoach” >

<constructor-arg ref=”myFortune”/>

</bean>

<bean id=”myFortune”

class=”com.spring.HappyFortuneService”>

</bean>

In Class:

public class TrackCoach implements Coach {

private FortuneService fortuneService;

public TrackCoach(FortuneService fortuneService) {

this.fortuneService = fortuneService;

}

}

In this above example, two beans are created one is myCoach and another is myFortune and we inject the dependency of HappyFortuneService class to the TrackCoach class with the help of constructor. In the TrackCoach class, we create a private field of FortuneService Interface and HappyFortuneService class implements this interface. with the help of the constructor, we initialize that.

In previously we made a HappyFortuneService object and provide it in the TrackCoach class manually using the ‘new’ keyword. This makes our application tightly coupled. If we make any changes in the future, then we have to change the rest of the code also.

But in the above example which is followed by nowadays, we don’t need to change the source code we just have to change the XML file where beans are created and managed.

2. Setter Injection: We can inject the dependency by the setter method also. The <property> subelement of <bean> is used for setter injection.

Example:

In .XML file:

<bean id=”myCricketCoach”

class=”com.luv2code.springdemo.CricketCoach”>

<property name=”fortuneService” ref=”myFortune”/>

</bean>

<bean id=”myFortune”

class=”com.spring.HappyFortuneService”>

</bean>

In Class:

public class CricketCoach implements Coach {

private FortuneService fortuneService;

public void setFortuneService(FortuneService fortuneService) {

this.fortuneService = fortuneService;

}

}

In this above example, two beans are created one is myCricketCoach and another is myFortune and we inject the dependency of HappyFortuneService class to the CricketCoach class with the help of the setter method. In the CricketCoach class, we create a private field of FortuneService Interface and HappyFortuneService class implements this interface. with the help of the setter method, we initialize that. Spring during injection search by the property name with first-word capital and adding set before that like in the above example the property name fortuneService which is mention in the myCricketCoach bean will become setFortuneService and this is the name of the method spring looking for.

So the above explanation is all about IoC and DI with XML configuration. nowadays most developers use Annotation-based configuration. Because it is easy to use and XML config becomes lengthy sometimes.

Conclusion :

Spring Inversion of Control(IOC) helps in the creation of loosely coupled applications because of Dependency Injection. By implementing Inversion of Control, software gets more controls.

--

--