Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring - Injecting Objects by Setter Injection

Injecting objects using setter injection in Spring means you're passing other beans as arguments to setter methods. This contrasts with constructor injection, where dependencies are provided through constructors.

Continuing with the Person and Address example:

1. Java Classes:

Address class:

public class Address {
    private String street;
    private String city;

    // Constructor, setters, getters, and other methods...

    @Override
    public String toString() {
        return street + ", " + city;
    }
}

Person class which depends on Address:

public class Person {
    private String name;
    private Address address;

    // Setter method for the Address dependency
    public void setAddress(Address address) {
        this.address = address;
    }

    // Setter method for name
    public void setName(String name) {
        this.name = name;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Address: " + address);
    }
}

2. XML Configuration:

Define the beans and their dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Definition for the address bean -->
    <bean id="addressBean" class="com.example.Address">
        <!-- Setter injection for Address properties can also be done if needed -->
    </bean>

    <!-- Definition for the person bean -->
    <bean id="personBean" class="com.example.Person">
        <property name="name" value="John Doe" />
        <property name="address" ref="addressBean" />
    </bean>

</beans>

In the XML:

  • The <property> tag with the name attribute set to name will use the setName method of the Person bean to set its name.
  • The <property> tag with the name attribute set to address and a ref attribute pointing to addressBean will use the setAddress method of the Person bean to inject the Address dependency.

3. Testing the Configuration:

To validate:

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

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        
        Person person = (Person) context.getBean("personBean");
        person.displayInfo();
    }
}

This should output:

Name: John Doe
Address: [The toString representation of the Address object]

Note:

Setter injection is suitable for optional dependencies or when there's a need to override certain default values that might have been set using a no-arg constructor or another setter method. If a dependency is crucial for the proper functioning of a bean, then constructor injection is a safer choice, as it ensures the bean always gets created with its required dependencies.

  1. Spring setter injection for objects:

    Setter injection in Spring involves providing dependencies through setter methods. It allows for flexible and optional dependency setting.

    public class UserService {
        private UserRepository userRepository;
    
        public void setUserRepository(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        // Other methods using userRepository
    }
    
  2. Setter-based dependency injection in Spring with objects:

    Setter-based injection is a common approach in Spring. Dependencies are set using setter methods.

    @Service
    public class UserService {
        private UserRepository userRepository;
    
        @Autowired
        public void setUserRepository(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        // Other methods using userRepository
    }
    
  3. Injecting custom classes in Spring setter methods:

    You can inject custom classes through setter methods in Spring:

    public class OrderService {
        private PaymentGateway paymentGateway;
    
        public void setPaymentGateway(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  4. Spring framework setter injection example with objects:

    Here's an example demonstrating setter injection in the Spring framework:

    @Service
    public class OrderService {
        private PaymentGateway paymentGateway;
    
        @Autowired
        public void setPaymentGateway(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  5. Setter injection for beans and objects in Spring:

    Setter injection is applicable not only for beans but also for objects in Spring:

    @Service
    public class ProductService {
        private ProductRepository productRepository;
    
        @Autowired
        public void setProductRepository(ProductRepository productRepository) {
            this.productRepository = productRepository;
        }
    
        // Other methods using productRepository
    }
    
  6. Injecting beans in Spring using setter methods:

    You can inject beans into Spring components using setter methods:

    @Service
    public class ShoppingCartService {
        private DiscountCalculator discountCalculator;
    
        @Autowired
        public void setDiscountCalculator(DiscountCalculator discountCalculator) {
            this.discountCalculator = discountCalculator;
        }
    
        // Other methods using discountCalculator
    }
    
  7. Spring bean configuration for setter injection with objects:

    XML configuration for setter injection in Spring:

    <beans>
        <bean id="userService" class="com.example.UserService">
            <property name="userRepository" ref="userRepository"/>
        </bean>
    
        <bean id="userRepository" class="com.example.UserRepository"/>
    </beans>
    
  8. Autowired setter injection with objects in Spring:

    @Autowired can be used with setter methods for automatic injection:

    @Service
    public class OrderService {
        private PaymentGateway paymentGateway;
    
        @Autowired
        public void setPaymentGateway(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  9. Injecting custom objects using @Autowired and setters in Spring:

    Custom objects can be injected using @Autowired and setter methods:

    @Service
    public class ShoppingCartService {
        private DiscountCalculator discountCalculator;
    
        @Autowired
        public void setDiscountCalculator(DiscountCalculator discountCalculator) {
            this.discountCalculator = discountCalculator;
        }
    
        // Other methods using discountCalculator
    }
    
  10. Creating and injecting custom objects in Spring setter methods:

    Custom objects can be created and injected through setter methods:

    @Service
    public class ProductService {
        private ProductRepository productRepository;
    
        @Autowired
        public void setProductRepository(ProductRepository productRepository) {
            this.productRepository = productRepository;
        }
    
        // Other methods using productRepository
    }