Skip to main content

Command Palette

Search for a command to run...

Spring Setter Injection Example

Updated
Spring Setter Injection Example
Y

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.

Date: 2017-09-18

Dependency Injection and Setter-Based Injection in Spring Framework: A Comprehensive Guide

Modern software design emphasizes modularity, a principle that promotes breaking down complex systems into smaller, manageable components. This modular approach is greatly facilitated by Dependency Injection (DI), a design pattern that manages the relationships between these components. This article will explore Dependency Injection, focusing on a specific implementation within the Spring Framework: Setter-Based Dependency Injection.

Dependency Injection, at its core, is about injecting dependencies between objects. Instead of an object creating its own dependencies, these dependencies are provided to it externally. This approach enhances modularity because components become less interdependent, more easily testable, and more reusable. Imagine a car: the engine, wheels, and steering wheel are all separate components that work together. DI is like providing the engine, wheels, and steering wheel to the car chassis, rather than having the chassis build them itself. This separation makes it easy to replace or test individual components without affecting the others.

There are two primary ways to implement Dependency Injection: Constructor Injection and Setter Injection. Constructor Injection involves passing dependencies directly to a class's constructor, effectively making dependencies mandatory for object creation. Setter Injection, the focus of this article, injects dependencies using setter methods, allowing for optional dependencies and potentially modifying them after object creation. Spring, a popular Java framework, supports both approaches, but often favors Setter Injection for its flexibility and readability.

Setter-based DI in Spring works by configuring the Spring container (a component responsible for managing and instantiating beans, or objects) to provide these dependencies. This configuration usually happens through an XML configuration file, although other methods exist. The Spring container creates instances of necessary classes (the "beans") and uses the setter methods of a dependent class to inject the required objects. This approach neatly separates the object creation and dependency management.

Let's consider a simple example: an Automated Teller Machine (ATM). An ATM interacts with a printer to display transaction information. In a traditional approach, the ATM class might create its own printer object. With Setter Injection, however, the Spring container would create both the ATM and Printer objects. The configuration would specify that the ATM requires a Printer, and the Spring container would inject the Printer object into the ATM using the ATM's setter method for the printer property. This eliminates the ATM's responsibility of creating the printer, making the ATM more focused on its core functionality—managing transactions.

The advantage of Setter Injection is clear: it offers a degree of flexibility not present in Constructor Injection. Optional dependencies can be omitted, and dependencies can be modified or re-injected even after the object has been created. This is particularly beneficial in dynamic environments where dependencies might change over time. The readability of the configuration files also tends to be better because the property names directly reflect the setter methods used.

To further illustrate, let's walk through a practical scenario of implementing Setter Injection in Spring using Java. We'll create a simple application with an Employee class and an AppMain class. The Employee class has properties like name, id, and salary, with corresponding setter methods. The AppMain class is responsible for retrieving the Employee bean from the Spring context (the container's configuration), setting its properties, and displaying the employee information. The configuration is specified in an XML file (e.g., spring-beans.xml), where we define the Employee bean, indicating the specific values for its properties. The Spring container will read this configuration, create the Employee object, set the properties via the setter methods, and make the object available to the AppMain class.

The process of setting up this project would typically involve creating a Maven project in an IDE like Eclipse. Maven simplifies dependency management; the pom.xml file would list necessary dependencies, such as the Spring Core and Spring Context libraries. These libraries provide the necessary classes and functionality for setting up the Spring container and managing beans. Next, Java classes would be created, corresponding to the design of the application. These Java classes would contain the code for managing the employee's details and the overall functionality of the application. The XML configuration file (spring-beans.xml) would detail how Spring should instantiate and configure the beans. This file acts as a blueprint for Spring, specifying how the beans are created, their properties, and their relationships. This file is crucial for setting up the dependency injection mechanism.

After creating the project structure, classes, and configuration file, the application can be run. The AppMain class would interact with the Spring container to access the configured Employee bean. The values specified in the spring-beans.xml would then be injected into the Employee object using the setter methods. The AppMain class could then display the employee information, demonstrating that the Setter Injection has successfully provided the dependencies. The output would display the employee's information as configured in the spring-beans.xml file, validating the successful implementation of Setter Injection.

In summary, Setter-Based Dependency Injection in the Spring framework provides a flexible and readable mechanism for managing dependencies between objects. By separating the creation of objects from their configuration, it promotes modularity, testability, and maintainability. The approach offers flexibility through optional dependencies and the ability to modify dependencies after object creation. Spring's reliance on XML configuration files (or other similar mechanisms) simplifies the management of dependencies, making it a powerful tool for building robust and scalable applications. The example outlined above provides a clear illustration of this powerful design pattern in a practical context.

Read more

More from this blog

The Engineering Orbit

1174 posts

The Engineering Orbit shares expert insights, tutorials, and articles on the latest in engineering and tech to empower professionals and enthusiasts in their journey towards innovation.