The Wayback Machine - https://web.archive.org/web/20241117195818/https://www.geeksforgeeks.org/spring-dependency-injection-with-example/
Open In App

Spring Dependency Injection with Example

Last Updated : 23 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from object creation and maintenance. These classes, managed by Spring, must adhere to the standard definition of Java-Bean. Dependency Injection in Spring also ensures loose coupling between the classes.

For developers aiming to master this critical aspect of Spring and implement it effectively in real-world applications, exploring a dedicated Java backend development course can offer in-depth knowledge and practical experience, enabling you to build modular, maintainable, and scalable applications with ease.

Need for Dependency Injection:

Suppose class One needs the object of class Two to instantiate or operate a method, then class One is said to be dependent on class Two. Now though it might appear okay to depend on a module on the other, in the real world, this could lead to a lot of problems, including system failure. Hence such dependencies need to be avoided. Spring IOC resolves such dependencies with Dependency Injection, which makes the code easier to test and reuse .

Loose coupling between classes can be possible by defining interfaces for common functionality and the injector will instantiate the objects of required implementation. The task of instantiating objects is done by the container according to the configurations specified by the developer.

Types of Spring Dependency Injection

There are two primary types of Spring Dependency Injection:

1. Setter Dependency Injection (SDI):

Setter DI involves injecting dependencies via setter methods. To configure SDI, the @Autowired annotation is used along with setter methods, and the property is set through the <property> tag in the bean configuration file.

package com.geeksforgeeks.org;

import com.geeksforgeeks.org.IGeek;
import org.springframework.beans.factory.annotation.Autowired;

public class GFG {

    // The object of the interface IGeek
    private IGeek geek;

    // Setter method for property geek with @Autowired annotation
    @Autowired
    public void setGeek(IGeek geek) {
        this.geek = geek;
    }
}

Bean Configuration:

<beans 
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="GFG" class="com.geeksforgeeks.org.GFG">
        <property name="geek">
            <ref bean="CsvGFG" />
        </property>
    </bean>
    
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
    
</beans>

This injects the CsvGFG bean into the GFG object using the setter method (setGeek).

2. Constructor Dependency Injection (CDI):

Constructor DI involves injecting dependencies through constructors. To configure CDI, the <constructor-arg> tag is used in the bean configuration file.

package com.geeksforgeeks.org;

import com.geeksforgeeks.org.IGeek;

public class GFG {

    // The object of the interface IGeek
    private IGeek geek;

    // Constructor to set the CDI
    public GFG(IGeek geek) {
        this.geek = geek;
    }
}

Bean Configuration:

<beans 
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="GFG" class="com.geeksforgeeks.org.GFG">
        <constructor-arg>
            <bean class="com.geeksforgeeks.org.impl.CsvGFG" />
        </constructor-arg>
    </bean>
    
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
    
</beans>

This injects the CsvGFG bean into the GFG object via the constructor.

Setter Dependency Injection (SDI) vs. Constructor Dependency Injection (CDI)

Setter DI Constructor DI
Poor readability as it adds a lot of boiler plate codes in the application. Good readability as it is separately present in the code.
The bean must include getter and setter methods for the properties. The bean class must declare a matching constructor with arguments. Otherwise, BeanCreationException will be thrown.
Requires addition of @Autowired annotation, above the setter in the code and hence, it increases the coupling between the class and the DI container. Best in the case of loose coupling with the DI container as it is not even required to add @Autowired annotation in the code.( Implicit constructor injections for single constructor scenarios after spring 4.0 )
Circular dependencies or partial dependencies result with Setter DI because object creation happens before the injections. No scope for circular or partial dependency because dependencies are resolved before object creation itself.
Preferred option when properties are less and mutable objects can be created. Preferred option when properties on the bean are more and immutable objects (eg: financial processes) are important for application.

Example of Spring DI:

  • We have used three classes and an interface as beans to exemplify the concepts of CDI and SDI. They are Vehicle, ToyotaEngine, Tyres classes and IEngine interface respectively.
  • From our example, we can see that class Vehicle depends on the implementation of the Engine, which is an interface. (So, basically, a Vehicle manufacturer wants a standard Engine which complies to Indian emission norms.) Class ToyotaEngine implements the interface and its reference is provided in the bean-configuration file mapped to one of Vehicle class’s properties.
  • In the Vehicle class, we invoke the application context and bean instantiation is executed. Two objects of class Vehicle are instantiated. ‘obj1’ is instantiated via bean with name InjectwithConstructor . The bean name could be located in the bean configuration file. Similarly ‘obj2’ is instantiated via bean with name InjectwithSetter .
  • It can be observed that ‘obj1’ is injected via the constructor and ‘obj2’ uses setter injection.
  • In the bean configuration file below, we have used two Vehicle beans’ declarations.
  • InjectwithConstructor bean makes use of element constructor-arg, with attributes name and ref. ‘Name’ attribute correlates with the constructor argument name given in the Vehicle class definition. And ‘ref’ attribute points to the bean reference which can be used for injecting.
  • InjectwithSetter makes use of property element to provide the ‘name’ of the property and the ‘value’ for the property. In place of value attribute ‘ref’ can be used to denote a reference to a bean.
  • In the configuration details, we are injecting ToyotaBean reference into the IEngine reference in Vehicle class constructor-arg, where IEngine is an interface and needs an implementing class reference for bean injection.
  • We have used two separate bean references for Tyres class, to inject via setter and constructor respectively. We can observe that ‘tyre1Bean’ and ‘tyre2Bean’ are initialized with String literal values for each of the properties.
Enigne.java
interface IEngine {
    String EMISSION_NORMS = "BSIV";
    String importOrigin();
    double cost();
}
ToyotaEngine.java
public class ToyotaEngine implements IEngine {
    String company;
    double cost;
    public double getCost()
    {
        return cost;
    }

    public void setCost(double cost)
    {
        cost = this.cost;
    }

    public String getCompany()
    {
        return company;
    }

    public void setCompany(String company)
    {
        this.company = company;
    }

    @Override
    public String importOrigin()
    {
        return "Japan";
    }

    @Override
    public double cost()
    {
        return cost;
    }
    @Override
    public String toString()
    {
        return "This is Engine object from: "
            + company;
    }
}
Tyres.java
public class Tyres {

    String name;
    String place;
    String message;

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getPlace()
    {
        return place;
    }
    public void setPlace(String place)
    {
        this.place = place;
    }
    public String getMessage()
    {
        return message;
    }
    public void setMessage(String message)
    {
        this.message = message;
    }

    @Override
    public String toString()
    {
        return "This is Tyre object: "
            + name + " " + place
            + " " + message;
    }
}
Vehicle.java
public class Vehicle {

    IEngine engine;
    Tyres tyre;

    public Tyres getTyre()
    {
        return tyre;
    }

    public void setTyre(Tyres tyre)
    {
        System.out.println("tyre instantiated via setter");
        this.tyre = tyre;
    }

    public Vehicle(IEngine engine, Tyres tyre)
    {
        System.out.println("instantiated via constructor");
        this.engine = engine;
        this.tyre = tyre;
    }

    public Vehicle() {}
    public IEngine getEngine()
    {

        return engine;
    }
    public void setEngine(IEngine engine)
    {
        System.out.println("instantiated via setter");
        this.engine = engine;
    }

    @Override
    public String toString()
    {
        return engine + " " + tyre;
    }

    public static void main(String a[])
    {
        ApplicationContext rootctx
            = new ClassPathXmlApplicationContext(
                "springContext.xml");

        // Instantiating the obj1 via Constructor DI
        Vehicle obj1
            = (Vehicle)rootctx
                  .getBean("InjectwithConstructor");

        // Instantiating the obj1 via Setter DI
        Vehicle obj2
            = (Vehicle)rootctx
                  .getBean("InjectwithSetter");

        System.out.println(obj1);
        System.out.println(obj2);
        System.out.println(obj1 == obj2);
    }
}
pom.xml
<dependencies>
  
    <!-- https:// mvnrepository.com/artifact
    /org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
  
    <!-- https:// mvnrepository.com/artifact
    /org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
</dependencies>
springContext.xml
< bean id="tyre1Bean" class="com.techgene.Tyres">
    <property name="name" value="MRF">
    </ property>

    <property name="place" value="India">
    </ property>

    <property name="message" value="Make in India">
    </ property>

</ bean>

< bean id="ToyotaBean" class="com.techgene.ToyotaEngine">
    <property name="company" value="Toyota">
    </ property>

    <property name="cost" value="300000.00">
    </ property>

</ bean>

< bean id="tyre2Bean" class="com.techgene.Tyres">
    <property name="name" value="TVS">
    </ property>

    <property name="place" value="India">
    </ property>

    <property name="message" value="Make in India">
    </ property>

</ bean>

< bean id="InjectwithSetter" class="com.techgene.Vehicle">
    <property name="engine" ref="ToyotaBean">
    </ property>

    <property name="tyre" ref="tyre1Bean">
    </ property>

</ bean>

< bean id="InjectwithConstructor" class="com.techgene.Vehicle">
    <constructor - arg name="engine" ref="ToyotaBean">
    </ constructor - arg>

    <constructor - arg name="tyre" ref="tyre2Bean">
    </ constructor - arg>
    
</ bean>


Process Flow:

The process flow of bean instantiation and injection of dependencies is given in the picture below:

Process Flow

Conclusion

Avoid using field injection as it improves readability but has several drawbacks. Combining setter and constructor injections is recommended. Use constructor injection for mandatory dependencies and setter injection for optional ones. Mandatory dependencies are crucial for business logic, while optional dependencies do not hinder core functionality if null.




Previous Article
Next Article

Similar Reads

Spring Dependency Injection: @Autowired vs Constructor Injection
In Spring framework, dependency injection is a key idea that lets you inject dependencies into a class in preference to hard coding them. This provides loose coupling and makes the code extra maintainable and testable. There are distinct methods to perform dependency injection. Common Approaches to Perform Dependency InjectionBelow is the list of
4 min read
Spring Boot - Dependency Injection and Spring Beans
Spring Boot is a powerful framework for building RESTful APIs and microservices with minimal configuration. Two fundamental concepts within Spring Boot are Dependency Injection (DI) and Spring Beans. Dependency Injection is a design pattern used to implement Inversion of Control (IoC), allowing the framework to manage object creation and dependenci
6 min read
Spring - Dependency Injection by Setter Method
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from objec
3 min read
Spring - Difference Between Inversion of Control and Dependency Injection
Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and Applic
4 min read
Spring - Difference Between Dependency Injection and Factory Pattern
Dependency Injection and Factory Pattern are almost similar in the sense that they both follow the interface-driven programming approach and create the instance of classes. A. Factory Pattern In Factory Pattern, the client class is still responsible for getting the instance of products by class getInstance() method of factory class, which means the
4 min read
Spring - When to Use Factory Design Pattern Instead of Dependency Injection
Prerequisite: Factory Pattern vs Dependency Injection Factory Design Pattern and Dependency Injection Design both are used to define the interface-driven programs in order to create objects. Dependency Injection is used to obtain a loosely coupled design, whereas the Factory Pattern adds coupling, between objects, factories, and dependencies. In th
2 min read
Spring - When to Use @Qualifier and @Autowired For Dependency Injection
In the world of Spring Framework, managing dependencies is a fundamental aspect of building robust and maintainable applications. Spring offers two primary annotations to facilitate dependency injection: @Autowired and @Qualifier. Understanding when and how to use these annotations is crucial for effective bean wiring .@Autowired and @Qualifier are
6 min read
Spring - Dependency Injection with Factory Method
Spring framework provides Dependency Injection to remove the conventional dependency relationship between objects. To inject dependencies using the factory method, we will use two attributes factory-method and factory-bean of bean elements. Note: Factory methods are those methods that return the instance of the class. Factory Method: These are thos
8 min read
Spring - Setter Injection vs Constructor Injection
Spring Framework is built on top of servlets and one of its main features is Dependency Injection (DI) it's one of the most common principles of modern software development and it allows us to achieve the principle of Inversion Of Control (IoC) i.e. shifting the creation, management and the lifecycle of objects from the programmer to the framework.
7 min read
private vs private-final injection of dependency
Dependency Injection (DI) is essential for improving code modularity, maintainability, and testability in the context of sophisticated Java programming. Choosing between private and private-final injection for dependencies is a typical DI concern. We will examine the distinctions between these two strategies in this post, as well as their applicati
5 min read
Generate Model Classes using jsonSchema2Pojo (website and Maven Dependency) For a Spring Boot Project That Consumes API
Generating Java model classes from a JSON schema is a common task when building applications that consume APIs, especially in Spring Boot projects. It simplifies the development process by mapping POJOs (Plain Old Java Objects) directly to the API's JSON structure. In this article, we explore how to use jsonSchema2Pojo, both as a web tool and as a
4 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Migrating a Spring Boot Application from Spring Security 5 to Spring Security 6
Spring Security is a powerful authentication and access control framework for Java applications specially for those built with the Spring Framework. With the release of Spring Security 6, several enhancements and changes have been introduced to simplify the security configuration and provide better performance and security features. This article ai
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Spring - Injecting Literal Values By Setter Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
4 min read
Spring - Constructor Injection with Collection
In the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the <constructor-a
2 min read
Spring - Injecting Objects by Setter Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Setter Injection with Dependent Object
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
3 min read
Spring - Constructor Injection with Dependent Object
In the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the <constructor-a
3 min read
Spring - Setter Injection with Non-String Collection
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
3 min read
Spring - Injecting Objects By Constructor Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Setter Injection with Map
Spring is an open-source lightweight framework that allows Java EE developers to build simple, reliable, and scalable enterprise applications. This framework is designed on the concept of Dependency Injection that focuses on providing various ways to manage business objects. Dependency Injection Dependency injection (DI) is a process where the obje
5 min read
Spring - Injecting Literal Values By Constructor Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Setter Injection with Non-String Map
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
3 min read
XML - Based Injection in Spring
In this article, we will be exploring XML-based Injection in Spring. and also creating a sample course management system using ApplicationContext that manages the complete lifecycle of a bean from its creation to destruction in a seamless manner. XML-based injectionXML-based injection refers to security vulnerabilities that can occur in Spring appl
4 min read
Spring - Constructor Injection with Map
In the Constructor Injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the <constructor-a
3 min read
Spring - Constructor Injection with Non-String Map
In the Constructor Injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean is done through the bean-configuration file. For this, the property to be set with the constructor dependency injection is declared under the <constructor-arg
4 min read
Why Is Field Injection Not Recommended in Spring?
Dependency Injection (DI) is a core concept in modern software development frameworks, particularly in Spring. It facilitates loose coupling, better testability, and easier maintenance. However, field injection is widely considered a poor practice compared to constructor and setter injection. This article explains why field injection in Spring is n
5 min read
Spring - Setter Injection with Collection
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
2 min read
Article Tags :
three90RightbarBannerImg