I explained in my previous post on Spring Framework [Dependency Injection] what is dependency injection? how spring finds the dependency? how does spring create and inject the service? etc. In this continued post, I will try to explain the three different ways of Dependency Injection.
- Field Injection: Using autowired annotation on a field.
- Method Injection: Using autowired annotation on a setter method.
- Constructor Injection: Using autowired annotation on a constructor.
The order in which the injection takes place is constructor followed by field and then method.
Autowired annotation on a field is explained here in my git hub code [Autowired Dependency] and in the previous Dependency Injection post. In this post, we will cover the setter and constructor dependency injection.
Setter Based Dependency Injection:
It is done by container calling the setter method on your bean after invoking a no argument constructor or a no argument static factory method to instantiate your bean. Example of setter based dependency injection is shown here on my git hub code: Setter DI Example
Constructor Based Dependency Injection:
It is done by container calling the parameterised constructor of the class with each parameter representing the dependency on another class. Example of constructor based dependency injection is shown here on my git hub code: Constructor DI Example Code and Constructor DI Example Test