How to inject beans using @Autowired annotation, if I use Lombok in the project?
The answers on these links seem to be unstable (support?):
Spring + Lombok: Can I have @Autowired @Setter
Spring support in IDEA with Lombok: Is "Navigate to autowired dependencies" supported?
Starting with Spring version 4.3, the single bean constructor does not need to be annotated with the @Autowired annotation.
This makes it possible to use the @RequiredArgsConstructor and @AllArgsConstructor annotations for dependency injection:
@Component
@RequiredArgsConstructor
public class Example {
private final ExampleDependency dependency;
public void example() {
dependency.call();
}
}
In the above example, Lombok will create a constructor with a single dependency field, and since this is the only constructor, Spring will inject the dependencies through it.
If your version of Spring is less than 4.3, or you use multiple constructors, you can annotate the desired Lombok constructor with the @Autowired annotation using the onConstructor field:
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
Constructor Injection in Spring with Lombok.
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