aliturgutb aliturgutb - 1 year ago 68
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 :

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?


Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download