Open In App

Spring – Injecting Literal Values By Constructor Injection

Last Updated : 14 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 Main Features of Spring IoC are as Follows:

  1. Creating Object for us,
  2. Managing our objects,
  3. Helping our application to be configurable,
  4. 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)

Tip: To read more on Spring Dependency Injection please refer to 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.

Here we will be discussing how to use Spring to inject our dependencies into our literal values by constructor Injection. Literals in Java are a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an integer value in the following statement.

int x = 100; 
// Here 100 is a constant/literal

Illustration:

String s = "Hello";

Implementation: We are conspiring the same example that we have created in this article Injecting Literal Values by Setter Injection. Create a simple class Student having two attributes id and studentName. Create setter methods for these two attributes and a simple method to print the details of the student.

A. File: Student.java 

Example:

Java




// Java Program to Illustrate Student Class
 
// Class
public class Student {
 
    // Class data members
    private int id;
    private String studentName;
 
    // Getters and setters
    public void setId(int id) { this.id = id; }
    public void setStudentName(String studentName)
    {
        // This keyword refers to current instance itself
        this.studentName = studentName;
    }
 
    // Method
    public void displayInfo()
    {
        // Printing name and corresponding
        // roll number of Student
        System.out.println("Student Name is " + studentName
                           + " and Roll Number is " + id);
    }
}


 
 

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>

 

Let us have a few illustrations for this project for which we can write something like below as follows:

 

Illustration 1-A:

 

<bean id="studentAmiya" class="Student">
  <constructor-arg name="id" value="101"/>
  <constructor-arg name="studentName" value="Amiya Rout"/>
</bean>

 

Similarly, we can create another bean and put the values like this

 

Illustration 1-B:

 

<bean id="studentAsish" class="Student">
  <constructor-arg name="id" value="102"/>
  <constructor-arg name="studentName" value="Asish Rout"/>
</bean>

 

So below is the complete code for the beans.xml file

 

B. File: beans.xml  

 

Example:

 

XML




<?xml version="1.0" encoding="UTF-8"?>
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 
    <bean id="studentAmiya" class="Student">
        <constructor-arg name="id" value="101"/>
        <constructor-arg name="studentName" value="Amiya Rout"/>
    </bean>
 
    <bean id="studentAsish" class="Student">
        <constructor-arg name="id" value="102"/>
        <constructor-arg name="studentName" value="Asish Rout"/>
    </bean>
 
</beans>


 
 

So now our two beans are ready. Now let’s create a class and define the main() method inside that class. Suppose we have created a class name Exam and we have defined the main() method inside this class. Below is the code for the Exam.java class. Comments are added inside the code for better understanding. 

 

C. File: Exam.java   

 

Example:

 

Java




// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Main class
public class Exam {
   
    // Main driver method
    public static void main(String[] args) {
       
        // Implementing Spring IoC
        // using ApplicationContext 
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
 
        // Getting the bean studentAmiya
        Student amiya = context.getBean("studentAmiya", Student.class);
         
        // Calling the methods
        // inside main() method
        amiya.displayInfo();
 
        // Getting the bean studentAsish
        Student asish = context.getBean("studentAsish", Student.class);
        
        // Calling the methods
        asish.displayInfo();
    }
}


 
 

Lastly, run the main() method and the output will be like this.

 

Output:

 

Student Name is Amiya Rout and Roll Number is 101
Student Name is Asish Rout and Roll Number is 102

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads