Setter Injections

This is another way to inject dependencies and its done by using a setter or getter methods to do so. We can do so by annotating a setter method with @Autowired and it’ll do the work. A key point here is that, dependencies will only be injecting when the setter/getter methods are called.

Assume that all the code will remain same we previously wrote for constructor injections except, I’ve provided a new concrete implementation Vivo & the REST Controller. There are only subtle modifications required in the REST Controller which I’ve made in below code:

Java




package com.w3wiki.SetterInjectionDemo;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
  
@RestController
@RequestMapping("/api")
public class RESTController {
    private SmartPhone mySmartPhone;
  
      //* Setter Injection *//
    @Autowired
    public void setSmartPhone(SmartPhone theSmartPhone)
    {
        this.mySmartPhone = theSmartPhone;
    }
  
    @GetMapping("/smartphone/name"
      public String getSmartPhoneName()
    {
        return mySmartPhone.getNameOfSmartPhone();
    }
}


Code Explanation:

  • Instead of having a constructor, here we have a setter method that injects the dependency because its annotated with @Autowired.
  • Breaking down how @Autowired is working here:

Working of @Autowired using setter injection

Code Explanation:

  • Firstly, the target class object is created
  • Secondly, the dependent class object is created
  • And finally, the dependencies are injected through setter method.

Output:

Output after calling the method

Note: Its not neccessary that we can only use setter method to inject dependencies instead, we can annotate any method with @Autowired and it’ll work as a dependency injection

3. Any method as the dependency injection

Any method name will work as long as the method that’s injecting dependencies is annotated with @Autowired

Java




//* Any method name will work *//
@Autowired
public void doSomething(SmartPhone theSmartPhone){
    this.mySmartPhone = theSmartPhone;
}


Now you maybe wondering which one should you choose while injecting dependencies ? So, here we’ve discussed below some parameter based differences between them :

Spring – Setter Injection vs Constructor Injection

Spring Framework is built on top of servlets and one of its main features is ‘Dependency Injection’ (DI) it’s one of the most common principles of modern software development and it allows us to achieve the principle of Inversion Of Control (IoC) i.e, shifting the creation, management and the lifecycle of objects from the programmer to the framework. This approach helps relieve the programmer from the responsibility of managing and creating objects and allows them to focus mainly on the business logic thereby effectively managing the objects. It’s also one of the core features of the spring-core module and aids in promoting decoupling among the components of our system. There are various ways in which we can do this, however, in this article, we’ll focus on Constructor and Setter Injections.

Pre-requisites:

1. Inversion Of Control Principle : In simple words, it is simply externalizing the creation & management of objects.
2. Dependency Injection : Dependency injection is basically wiring various objects altogether to support a single cause.

The below image briefly explains the principle of IoC, that we only need to ask for what object we want, and our spring container will return an instance of it.

Inversion Of Control

To summarize, the whole idea of saying – “hey, give me a smart phone object” is that if the object has any helper components or other dependencies, then assemble them ahead of time and provide me the object whenever I ask on demand or when another dependent object is created. There are 3 types of configuration mainly used :

1. XML Based Configuration (Legacy)
2. Java-Based Configuration (Modern)
3. Annotation Based Configuration (Modern)

In this article, we’ll be using Annotation based configuration.

Similar Reads

Step-by-Step Procedure

1. Go to Spring Initializr tool...

Constructor Injection

In this method, dependencies are passed as a parameter to the class’s constructor. This ensures that all the dependencies are injected upon the instantiation of an object. We utilise the @Autowired Annotation on top of the constructors to achieve this....

Setter Injections

...

Setter Injections v/s Constructor Injections

...

Use cases when to use which one?

...