Alex Man
Alex Man

Reputation: 4886

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

Upvotes: 2

Views: 6632

Answers (3)

Hafiz Hamza
Hafiz Hamza

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

Victor1125
Victor1125

Reputation: 692

Yes, you're right - you don't need use annotation @Autowired constructor with DI. I think is couple of reasons:

  • developer doesn't known that is not necessairy
  • developer use annotation to emphasize that it's DI
  • the programmer doesn't trust Spring and wants to make sure DI works
  • application was written in lower Spring and upgraded to newer - annotation is artifact of it

Upvotes: 2

dunni
dunni

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

Related Questions