aliturgutb aliturgutb - 7 days ago 5
Java Question

Which kind of injection? Setter or constructor injection?

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

@Autowired
Iservice service;


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

Behind science which injection method Spring uses? 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).

Comments