Monday, November 18, 2024
Google search engine
HomeLanguagesJavaSpring – Injecting Objects by Setter Injection

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) 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

Setter Injection

Setter Injection is the simpler of the two  Dependency Injection methods. In this, the Dependency Injection will be injected with the help of setter and/or getter methods. Now to set the Dependency Injection as Setter Injection in the bean, it is done through the bean-configuration file For this, the property to be set with the Setter Injection is declared under the <property> 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.

Example 1:

Java




// Java Program to Illustrate Student File
 
// Class
public class Student {
 
    // Attributes
    private int id;
    private MathCheat mathCheat;
 
    // Method
    public void cheating()
    {
        System.out.println("My ID is: " + id);
        mathCheat.mathCheating();
    }
}


Example 2:

Java




// Java Program to Illustrate MathCheat File
 
// Class
public class MathCheat {
 
    // Method
    public void mathCheating()
    {
        // Print statement
        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 Setter Dependency Injection. So at first, we have to create the setter method inside the Student.java file. Now the Student.java file is something like this.

Example 1:

Java




// Java Program to Illustrate Student File
 
// Class
public class Student {
 
    // Attributes
    private int id;
    private MathCheat mathCheat;
 
    // Setter
    public void setId(int id) { this.id = id; }
 
    // Setter
    public void setMathCheat(MathCheat mathCheat)
    {
        this.mathCheat = mathCheat;
    }
 
    // Method
    public void cheating()
    {
 
        // Print statement
        System.out.println("My ID is: " + id);
       
        mathCheat.mathCheating();
    }
}


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 <property> tag, like this

Syntax: Standard 

<bean id="AnyUniqueId" class="YourClassName">

  <property name="attributes that you have defined 
  in your class" value="And its corresponding values"/>
  
</bean>

But here we are injecting objects, not literal values as we have done in this article Injecting Literal Values by Setter Injection. So for this example, we can write something like this

<bean id="student" class="Student">
      <property name="id" value="101"/>
      <property name="mathCheat">
        <bean class="MathCheat"></bean>
      </property>
</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">
        <property name="id" value="101"/>
        <property name="mathCheat">
            <bean class="MathCheat"></bean>
        </property>
    </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.

Example

Java




// Java Program to Illustrate Main File
// Implementing Spring IoC
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Main class
public class Main {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Using ApplicationContext to
        // Implementing Spring IoC
        ApplicationContext context
            = new ClassPathXmlApplicationContext(
                "beans.xml");
 
        // Getting the bean student
        Student student
            = context.getBean("student", Student.class);
 
        // Calling the 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">
    <property name="id" value="101"/>
    <property name="mathCheat" ref="mathCheatObjectValue"/>
</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="mathCheatObjectValue" class="MathCheat"></bean>
 
    <bean id="student" class="Student">
         <property name="id" value="101"/>
         <property name="mathCheat" ref="mathCheatObjectValue"/>
    </bean>
 
</beans>


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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments