Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why people uses @Autowired for constructor injection

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

like image 382
Alex Man Avatar asked Dec 06 '25 04:12

Alex Man


1 Answers

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.

like image 106
dunni Avatar answered Dec 07 '25 18:12

dunni