
What are the types of Spring Dependency Injection?
Setter Based Injection
When Spring Container provides values to variables using setter method, we call it Setter Injection. In this case, Spring Container uses the default constructor to create the object. When the annotation @Autowired is used on top of the class’s setter method, it is known as Setter based Dependency Injection.
@Component
public class Vendor{
int code;
String name;
}
public class Invoice{
private Vendor vendor;
@Autowired
public void setVendor(Vendor vendor){
this.vendor=vendor;
}
}As shown in the example above, Vendor class has been created using @Component annotation. Hence, Spring container will automatically detect it while starting up the application and will create a bean object for Vendor class. Further, when Spring container detects that the Vendor bean object has been Autowired (using @Autowired) into Invoice class setVendor() method, the bean object created for Vendor will be injected into Invoice class via setter method.
Constructor Based Injection
When Spring Container provides values to variables using parameterized constructor, we call it Constructor Injection. Please note that Spring Container uses parameterized constructor to create the object in this case. When the annotation @Autowired is used on top of the class constructor, it is known as Constructor-based Dependency Injection.
@Component
public class Vendor{
int code;
String name;
}
public class Invoice{
private Vendor vendor;
@Autowired
public Invoice(Vendor vendor){
this.vendor=vendor;
}
}As shown in the example above, Vendor class has been created using @Component annotation. Hence, Spring container will automatically detect it while starting up the application and will create a bean object for Vendor class. Further, when Spring container detects that the Vendor bean object has been Autowired (using @Autowired) into Invoice class constructor, the bean object created for Vendor will be injected into Invoice class via constructor.
Field or Property Based Injection
When the annotation @Autowired is used on top of the field or property in the class, it is known as Field-based Dependency Injection.
@Component
public class Vendor{
int code;
String name;
}
public class Invoice{
@Autowired
private Vendor vendor;
}Similar to above both Dependency Injection, here the Autowiring takes place by means of the field ‘vendor’. The bean object created for Vendor class will be Autowired & injected via the field, ‘vendor’ in Invoice class.
In this case, while creating the Invoice object, if there’s no constructor or setter method is available to inject the Vendor bean, the container will use reflection to inject Vendor into Invoice.