What is the benifit of using @Autowired on constructor as below,
@Autowired
public MyClass(A a){
}
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.
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.
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