Lombok and @Autowired

Viewed 9459
3 Answers

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.

As of Spring 4.3, if a class defines only one single constructor, Spring will understand to use that constructor without needing to add @Autowired or any other annotations. Simply ensure that you have an appropriate constructor.

As mentioned by @vszholobov, you can use @RequiredArgsConstructor or @AllArgsConstructor; it's usually best to make your dependencies final, so unless you have something like a default Clock, they'll be basically equivalent. (This also works with other styles of creating constructors, such as @TupleConstructor(defaults = false) for Groovy.)

In older versions of Spring you'll need Lombok to annotate the constructor with @Autowired e.g. @AllArgsConstructor(onConstructor = @__(@Autowired)).

Related