Tutorials

Setter Injection


SI Primitive values


In the Dependency Injection section of this tutorial, we have already learnt that Setter Injection can be used to inject primitive values, object dependencies and collections.

In this section, we will learn about the process of injecting the primitive values in Spring using setter injection or SI.

 

Injecting Primitive values

We can inject primitive values as argument through setter injection.

 

All we need to have for our demonstration is:

  1. A POJO class - This class will have setter properties that would help inject primitive values. For keeping things simple we have just two properties in this class for now. In upcoming chapters of this tutorials, we will have multiple properties. 
  2. XML Configuration file - Most commonly this file is named as "applicationContext.xml" or "appContext.xml". Its just a suggestion, you can name it whatever you want. This file contains meta-data for the container to let it know the beans to create, the dependencies between several beans, how to wire them together, bean scope, etc. 
  3. Test class - This class will first load the xml configuration file (applicationContext.xml) and then would call the bean by its name. It will use the bean to call the methods of the class to which this bean is mapped.

 

Java POJO - Subjects.java


package com.javaradar.constructorInjection;

public class Subjects {

      private String subjectName;
      private int subjectID; 
    
      public String getSubjectName() {
            return subjectName;
      }

      public void setSubjectName(String subjectName) {
            this.subjectName = subjectName;
      }

      public int getSubjectID() {
            return subjectID;
      }

      public void setSubjectID(int subjectID) {
            this.subjectID = subjectID;
      }

      public void displayDetails(){
            System.out.println("Subject Name:"+ subjectName);
            System.out.println("Subject Name:"+ subjectID);
      }

}

XML Configuration

Source File Name: applicationContext.XML

setter injection in spring by tutorialsinhand.com

 

 
 

Test Class: TestSubjects.java


package com.javaradar.constructorInjection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSubjects {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Subjects subBean = (Subjects) context.getBean("SubjectsBean");
        subBean.displayDetails();
                               
     }

}

OUTPUT:

Subject Name:Spring
Subject Name:1001

 

 

 

 

 



Please Share this page
Views : 78
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!