Field-based DI
In the preceding sections, we saw how we can use constructor-based and setter-based dependencies in our application. In the following example, we will see field-based DI. Actually, field-based DI is easy to use, and it has clean code compared to the other two types of injection method; however, it has several serious trade-offs, and should generally be avoided.
Let's look at the following example of a field-based DI. In the following code, we will see how to use a field for injecting a CustomerService object in the BankingService class:
@Component
public class BankingService {
//Field based Dependency Injection
@Autowired
private CustomerService customerService;
public void showCustomerAccountBalance() {
customerService.showCustomerAccountBalance();
}
}
As we discussed, this type of DI has the benefit of removing clutter code over setter-or constructor-based dependencies, but it has many drawbacks, such as dependencies are invisible from the outside. In constructor-based and setter-based dependencies, classes clearly expose these dependencies using the public interface or setter method. In a field-based DI, the class is inherently hiding the dependencies from the outside world. Another difficulty is that field injection cannot be used to assign dependencies to final/immutable fields, as these fields must be instantiated at class instantiation.
Generally, Spring discourages the use of the field-based dependency.
Here is a diagram with the different types of DI that we have learned about so far: