Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - Injecting Objects by Setter Injection

In Spring, setter injection is a technique where the Spring container injects the dependencies of a bean through its setter methods. This approach is suitable when you have optional dependencies for a bean or when you prefer more flexibility in configuring the bean post-instantiation.

Let's discuss how to inject objects using setter injection in Spring:

XML Configuration:

1. Java Classes:

Suppose we have a Person class and an Address class:

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

    // constructors, getters, setters...
}

public class Person {
    private Address address;

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

    // getters, other methods...
}

2. Spring XML Configuration:

<bean id="address" class="com.example.Address">
    <property name="city" value="New York" />
    <property name="country" value="USA" />
</bean>

<bean id="person" class="com.example.Person">
    <property name="address" ref="address" />
</bean>

In the XML configuration, the property element with the name attribute matching the bean's property name and the ref attribute pointing to another bean tells Spring to use the setter method to inject the address bean into the person bean.

Java-based Configuration:

For Java-based configurations, you can use the @Bean annotation to define the beans and set the properties:

@Configuration
public class AppConfig {

    @Bean
    public Address address() {
        return new Address("New York", "USA");
    }

    @Bean
    public Person person() {
        Person person = new Person();
        person.setAddress(address());
        return person;
    }
}

In the Java configuration, after creating an instance of Person, you're setting the address property using the provided setter method.

Annotation-based Configuration:

When using annotation-driven configurations with component scanning, you can achieve setter injection with the @Autowired annotation:

@Component
public class Address {
    private String city = "New York";
    private String country = "USA";

    // getters, setters, other methods...
}

@Component
public class Person {
    private Address address;

    @Autowired
    public void setAddress(Address address) {
        this.address = address;
    }

    // getters, other methods...
}

By placing the @Autowired annotation on the setter method, you're instructing Spring to autowire the Address bean into the Person bean using that setter method.

Conclusion:

Setter injection provides flexibility and is recommended for optional dependencies or for cases where you want to override certain properties post bean instantiation. It's also a practical choice when dealing with legacy code that might not have suitable constructors for injection. However, for mandatory dependencies and to promote immutability, constructor injection is often preferred.

  1. Injecting dependencies with setter injection in Spring:

    • Description: Setter injection is a mechanism in Spring where dependencies are provided to a bean through setter methods. This allows for more flexibility and is particularly useful when dealing with optional or changeable dependencies.

    • Code Example:

      public class OrderService {
          private PaymentService paymentService;
      
          // Setter injection
          public void setPaymentService(PaymentService paymentService) {
              this.paymentService = paymentService;
          }
      
          // ...
      }
      
  2. How to pass objects through setters in Spring:

    • Description: Objects can be passed to a bean through setter methods during the instantiation or after the bean is created. This promotes a more dynamic way of configuring beans with their dependencies.

    • Code Example:

      public class CustomerService {
          private AddressService addressService;
      
          // Setter method with an object parameter
          public void setAddressService(AddressService addressService) {
              this.addressService = addressService;
          }
      
          // ...
      }
      
  3. Configuring setter injection with other beans in Spring:

    • Description: Setter injection allows you to configure a bean with references to other beans. This establishes relationships between components and enables the Spring container to manage their lifecycle.

    • Code Example:

      public class ShoppingCart {
          private ProductService productService;
      
          // Setter injection with another bean
          public void setProductService(ProductService productService) {
              this.productService = productService;
          }
      
          // ...
      }
      
  4. Using @Autowired annotation for setter injection in Spring:

    • Description: The @Autowired annotation can be used for setter injection, allowing Spring to automatically resolve and inject the required dependencies.

    • Code Example:

      public class OrderProcessor {
          private ShippingService shippingService;
      
          // Setter injection using @Autowired
          @Autowired
          public void setShippingService(ShippingService shippingService) {
              this.shippingService = shippingService;
          }
      
          // ...
      }
      
  5. Setter injection with custom objects in Spring XML configuration:

    • Description: In Spring XML configuration, setter injection with custom objects is achieved by specifying the object references within the <property> elements.

    • XML Configuration Example:

      <bean id="orderService" class="com.example.OrderService">
          <property name="paymentService" ref="paymentService" />
      </bean>
      
  6. Injecting dependencies through setters in Spring:

    • Description: Setter injection is a common approach for injecting dependencies into Spring beans. It allows for more flexibility and maintainability, especially when dealing with a large number of dependencies.

    • Code Example:

      public class ProductService {
          private CategoryService categoryService;
      
          // Setter injection with dependency
          public void setCategoryService(CategoryService categoryService) {
              this.categoryService = categoryService;
          }
      
          // ...
      }
      
  7. Dynamic object injection using placeholders in Spring setters:

    • Description: Spring allows dynamic object injection using placeholders, which can be resolved from property files or system properties. This provides flexibility in configuring beans with values determined at runtime.

    • Code Example:

      public class ReportingService {
          private String reportType;
      
          // Setter injection with placeholders
          @Value("${report.type}")
          public void setReportType(String reportType) {
              this.reportType = reportType;
          }
      
          // ...
      }
      
  8. Examples of setter injection with objects in Spring:

    • Example 1:

      public class UserService {
          private EmailService emailService;
      
          // Setter injection with another bean
          public void setEmailService(EmailService emailService) {
              this.emailService = emailService;
          }
      
          // ...
      }
      
    • Example 2:

      public class LoggerService {
          private LogRepository logRepository;
      
          // Setter injection with a custom object
          public void setLogRepository(LogRepository logRepository) {
              this.logRepository = logRepository;
          }
      
          // ...
      }