Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of @Autowired on constructor [closed]

Tags:

java

spring

What is the benifit of using @Autowired on constructor as below,

@Autowired
public MyClass(A a){
} 
like image 325
Harshana Avatar asked Aug 02 '16 09:08

Harshana


2 Answers

This way bean A will be injected into the constructor. It is cleaner because you kind of declare the dependencies of the bean, because it can't be instantiated without supplying A. This makes testing a lot easier.

like image 98
Predrag Maric Avatar answered Sep 28 '22 15:09

Predrag Maric


You can have final fields in the class, and generally even immutable class - less moving parts, cleaner code, easier to understand.

And the class is easier to test, you always know what properties to set in it to have a working class (because constructor forces you to set those) - of course one might still pass nulls in the params.

like image 30
Krzysztof Krasoń Avatar answered Sep 28 '22 14:09

Krzysztof Krasoń