Search code examples
javaspringlombokinject

What is the difference between @RequiredArgsConstructor(onConstructor = @__(@Inject)) and @RequiredArgsConstructor?


What is the difference between Lombok's

@RequiredArgsConstructor 

and

@RequiredArgsConstructor(onConstructor = @__(@Inject))

I know that RequiredArgsConstructor injects all the final dependencies in constructor only.


Solution

  • @RequiredArgsConstructor
    class MyClass {
      private final DependencyA a;
      private final DependencyB b;
    }
    

    will generate

    public MyClass(DependencyA a, DependencyB b) {
      this.a = a;
      this.b = b;
    }
    

    while

    @RequiredArgsConstructor(onConstructor = @__(@Inject))
    class MyClass {
      private final DependencyA a;
      private final DependencyB b;
    }
    

    will generate

    @Inject
    public MyClass(DependencyA a, DependencyB b) {
      this.a = a;
      this.b = b;
    }
    

    From JDK 8 onwards, the syntax @RequiredArgsConstructor(onConstructor_ = {@Inject}) is also accepted.

    I know RequiredArgsConstructor injects all the final dependencies.

    All required dependencies which consists of final and @NonNull fields.