I have seen many people using @Autowired annotation in constructor to inject dependencies like as shown below
@Service
public class Employee {
private EmployeeService employeeService;
@Autowired
public Employee(EmployeeService employeeService) {
this.employeeService = employeeService;
}
:
:
}
as per my knowledge nowadays Spring is so advanced and the Spring constructor/setter DI works even without @Autowired like as shown below
@Service
public class Employee {
private EmployeeService employeeService;
public Employee(EmployeeService employeeService) {
this.employeeService = employeeService;
}
:
:
}
Like to know is there any reason why people annotate constructor with @Autowired annotation to inject dependencies.
Can someone please help me on this
There is no technical reason to do this (except if you have multiple constructors etc.). The most likely reason is, that people have learned to use it, when Spring didn't support the autodetection of the constructor and when it was still necessary, and as the saying goes, old habits die hard. Also, if you search for any examples, you still find a lot of tutorials, where the annotation is used, so that is another reason. It's the same as with the @Repository annotation on Spring Data interfaces. That annotation is just plain wrong there, but there are a lot of questions on this site, where people added this in their code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With