VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/spring-dependency-injection-by-setter-method/

⇱ Spring - Dependency Injection by Setter Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Spring - Dependency Injection by Setter Method

Last Updated : 30 Oct, 2025

Dependency Injection is a design pattern where the Spring IoC container is responsible for providing the required dependencies of a class rather than the class creating them itself.

Instead of manually instantiating objects, Spring automatically injects them at runtime, either through constructors or setter methods.

Why use Dependency Injection?

Without DI, classes are tightly coupled since they instantiate their dependencies directly:

This approach makes testing and maintenance difficult.

With Spring DI, the container injects dependencies externally:

Now, A and B are loosely coupled. The Spring container manages their lifecycle and relationships.

Types of Dependency Injection in Spring

There are two types of dependency injection in spring

  • Constructor-Based Dependency Injection: Dependencies are injected using a constructor.
  • Setter-Based Dependency Injection: Dependencies are injected using setter methods.

Types of Dependency Injection in Spring

  • Constructor-Based Injection: Dependencies are injected via the class constructor.
  • Setter-Based Injection: Dependencies are injected via setter methods after object creation.

Setter-Based Dependency Injection

In Setter-Based DI, the Spring container:

  1. Creates a bean using a no-argument constructor.
  2. Calls setter methods to inject dependencies.

XML-Based Setter Injection

Dependencies are injected into a bean using setter methods defined in the Spring configuration XML file. The Spring container creates the bean instance and assigns property values using <property> tags.

Step 1: Create a POJO Class

Student.java:

Step 2: Create the Spring Configuration File (config.xml)

Step 3: Main Application

Output:

Student{studentName=John, studentCourse=Spring Framework}

Annotation-Based Setter Injection

In modern Spring applications, annotations are preferred over XML. The same example can be implemented as follows:

Step 1: Enable Component Scanning

Step 2: Annotate the Class

Step 3: Main Application

Output:

Student{studentName=John, studentCourse=Spring Framework}

Java-Based Configuration

Java-based configuration replaces XML with annotations and Java classes.

Step 1: Configuration Class

Step 2: Main Application

Output:

Student{studentName=John, studentCourse=Spring Framework}

Advantages of Setter-Based Dependency Injection

  • Loose Coupling: Reduces dependencies between classes.
  • Flexibility: Properties can be modified after bean creation.
  • Ease of Testing: Allows mock dependencies to be injected easily.
  • Configuration Simplicity: Beans and dependencies can be configured externally.
Comment
Article Tags:

Explore