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.

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



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


More details about setter injection is provided in the respective section of this spring tutorial.


Please Share this page
Views : 63
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!