What is the difference between anotate @Autowired to a property or do it in the setter?
As far as I know they both have the same result, but is there any reason to use o
There are 3 types of autowiring:
@Autowired
private MyService service;
@Autowired
annotation in this case:class MyController {
private final MyService service;
public MyController(MyService service) {
this.service = service;
}
}
private MyService service;
@Autowired
public void setService(MyService service) {
this.service = service;
}
It is recommended to use Constructor based, then if not possible, Setter based and lastly Property based.
Why?
First, because in Constructor based you don't even use any Spring annotations. This helps you transition to different frameworks.
Second, Constructor or Setter based, make unit testing much easier. You don't need to use any Spring specific testing tools and you can only use Junit and Mockito.
Third, Constructor based is good because you can declare the property as final
and not expose setters which helps with immutability and thread safety of the class.