The Wayback Machine - https://web.archive.org/web/20240906002548/https://www.geeksforgeeks.org/spring-injecting-objects-by-constructor-injection/
Open In App

Spring – Injecting Objects By Constructor Injection

Last Updated : 29 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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) or Java Code or Java Annotations and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control. The followings are some of the main features of Spring IoC.

  • Creating Object for us,
  • Managing our objects,
  • Helping our application to be configurable,
  • Managing dependencies

Spring Dependency Injection

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. There are two types of Spring Dependency Injection.

  • Setter Dependency Injection (SDI)
  • Constructor Dependency Injection (CDI)

To read more on Spring Dependency Injection please refer to this article: Spring Dependency Injection with Example

Constructor Injection

In Constructor Injection, the Dependency Injection will be injected with the help of constructors. Now to set the Dependency Injection as Constructor Dependency Injection in bean, it is done through the bean-configuration file. For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file.

So in this article, let’s learn how we are going to use Spring to inject our dependencies into our object values by Setter Injection. Object is a basic unit of Object-Oriented Programming and represents real-life entities. So generally in Java, we create objects of a class using the new keyword.

Test t = new Test();
// creating object of class Test
// t is the object

Implementation: Suppose we have a class named “Student” and inside the class, we want to inject the object of another class named “MathCheat”. And there is one method also present inside the class named “cheating()” something like that.

File: Student.java

public class Student 
{
    // Class data members
    private int id;
    private MathCheat mathCheat;

    // Method
    public void cheating() 
    {

        System.out.println("My ID is: " + id);

        mathCheat.mathCheating();
    }

}

File: MathCheat.java

public class MathCheat 
{
    public void mathCheating() 
    {
        System.out.println("And I Have Stated Math Cheating");
    }
}

So now we want to inject the object of MathCheat into the Student class by using the concept of Constructor Dependency Injection. So at first, we have to create the constructor inside the Student.java file. Now the Student.java file is something like this.

Java




// Java Program to Illustrate Student class
 
public class Student {
 
    // Class data members
    private int id;
    private MathCheat mathCheat;
 
    // Constructor of Student class
    public Student(int id, MathCheat mathCheat)
    {
        this.id = id;
        this.mathCheat = mathCheat;
    }
 
    // Method
    public void cheating()
    {
        System.out.println("My ID is: " + id);
        mathCheat.mathCheating();
    }
}


 
 

The only thing we need to change is in the beans.xml file. Now let’s create a Student Bean in the beans.xml file and inside the bean, you have to add your property’s name and its corresponding values inside the <constructor-arg> tag instead of the <property> tag, like this

 

Syntax: Standard 

 

<bean id="AnyUniqueId" class="YourClassName">
  <constructor-arg name="attributes that you have defined in your class" value="And its corresponding values"/>
</bean>

 

For example: For this project, we can write something like this

 

<bean id="student" class="Student">
    <constructor-arg name="id" value="101"/>
    <constructor-arg name="mathCheat">
       <bean class="MathCheat"></bean>
    </constructor-arg>
</bean>

 

You can see how we created the bean of MathCheat class inside the Student bean. Below is the complete code for the beans.xml file

 

XML




<?xml version="1.0" encoding="UTF-8"?>
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 
    <bean id="student" class="Student">
        <constructor-arg name="id" value="101"/>
        <constructor-arg name="mathCheat">
            <bean class="MathCheat"></bean>
        </constructor-arg>
    </bean>
 
</beans>


 
 

So for testing this stuff let’s create a main method and call the cheating() method inside the Student class. Below is the code for the Main.java file.

 

Application File 

 

Java




// Java Program to Illustrate Application Class
 
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Application class
// GFG class
public class Main {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Implementing Spring IoC
        // Using ApplicationContext
        ApplicationContext context
            = new ClassPathXmlApplicationContext(
                "beans.xml");
 
        // Getting the bean student
        Student student
            = context.getBean("student", Student.class);
 
        // Calling the method inside main() method
        student.cheating();
    }
}


 
 

Output:

 

My ID is: 101
And I Have Stated Math Cheating

Another Approach (Right Approach)

 

So there is another approach to create the bean of  MathCheat class inside the beans.xml file. So you can write something like this using the “ref“. 

 

<bean id="mathCheatObjectValue" class="MathCheat"></bean>


<bean id="student" class="Student">
    <constructor-arg name="id" value="101"/>
    <constructor-arg name="mathCheat" ref="mathCheatObjectValue"/>
</bean>

 

Below is the complete code for the beans.xml file.

 

Example:

 

XML




<?xml version="1.0" encoding="UTF-8"?>
       xsi:schemaLocation="http://www.springframework.org/schema/beans
     
    <bean id="mathCheatObjectValue" class="MathCheat"></bean>
 
    <bean id="student" class="Student">
         <constructor-arg name="id" value="101"/>
         <constructor-arg name="mathCheat" ref="mathCheatObjectValue"/>
    </bean>
 
</beans>


 
 

So whenever you are going to run your application you are going to get the same output. Example

 



Previous Article
Next Article

Similar Reads

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 - 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 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 - 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
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 &lt;constructor-a
2 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 &lt;constructor-a
3 min read
Spring - Constructor 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 the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as cons
3 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 &lt;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 &lt;constructor-arg
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 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 &lt;?xml version=&quot;1.0&quot; 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
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 - 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 - 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 - 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 - 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 - 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 - 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
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
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 - 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 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
Spring Dependency Injection with Example
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
8 min read
YAML to List of Objects in Spring Boot
In this article, let us dive into Converting YAML files to a List of Objects in Spring boot. To understand this we need to have some knowledge of the following pre-requisites. YAML: YAML represents a key-value structure that is human-readable data serializable format. The features of YAML includingReadability,Ease of writingUnderstanding makes it a
7 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read