Reputation: 4886
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
Upvotes: 2
Views: 6632
Reputation: 309
Personally, I use @Autowired
annotation just to enhance code readability so that other developers can read and understand code more easily.
Upvotes: 1
Reputation: 692
Yes, you're right - you don't need use annotation @Autowired
constructor with DI.
I think is couple of reasons:
Upvotes: 2
Reputation: 44515
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.
Upvotes: 9