Dependency Injection

Setter Injection

When we inject dependency through setter method then this type of dependency injection (DI) is known setter injection.

The  tag inside bean element is used to inject the dependencies.


The setter injection allows injecting following dependency:

  • primitive or String values
  • objects
  • Collections

We will learn only primitive value injection in this chapter of the tutorial. 

Object and collection dependency injection through setter will be explained in the respective sections of this tutorial.

Injecting Primitive Values

We can inject primitive values as argument through constructor injection as explained below:


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


You need to copy the below XML in your applicationContext.XML file and then create the bean dependencies as shown in above image.


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



Subject Name:Spring
Subject Name:1001




Please Share this page
Views : 7