aliturgutb aliturgutb - 11 days ago 7
Java Question

Which kind of injection does Spring use with @Autowired? Setter or constructor injection?

I have a CarService interface and that is implemented by CarServiceImpl class with @Service annotation. In my Component class with @Component annotation, I use :

@Autowired
CarService carService;


And it is working well, i can use carService object that is instance of CarServiceImpl Class. The question in my mind is :

Behind science which injection method does Spring use? Setter injection or constructor injection?

Thanks.

Answer

This is using field injection, in which Spring directly reaches into the class and manipulates its fields. It is far preferable to use constructor injection for required dependencies, which makes the dependency explicit and helps identify injection problems at the earliest possible point. Lombok can make this as simple as annotating the class with @RequiredArgsConstructor (Spring doesn't need annotations on the constructor if there's only one).