What is the difference between @RequiredArgsConstructor(onConstructor = @__(@Inject)) and @RequiredArgsConstructor?
@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 include final
and @NonNull
fields.
The answers given have explained clearly what is the difference as asked by the OP. But i also feel that knowing why you would need @RequiredArgsConstructor(onConstructor = @__(@Inject))
instead of @RequiredArgsConstructor
? is also important. If you are interested, read on...
In short, when Spring construct your beans (the classes annotated with @Component or related @Controller, @Service, @Repository - they all have @Component + extra functionality), Spring will need to look at the class constructor, to construct it. If you have only 1 constructor in your class, fine, no confusion, you only need @RequiredArgsConstructor
.
What if you have 2 or more constructors? Which one does Spring use to construct your bean? Enter Lombok's @RequiredArgsConstructor(onConstructor = @__(@Inject))
or the more popular @RequiredArgsConstructor(onConstructor = @__(@Autowired))
. As the annotation's attribute says, it puts @Autowired on the constructor to tell Spring to use that constructor at construction time.
That's it!
P.S I recommend this article if you want to read more about it.
The second one will put the annotations you mention on the generated constructor.
For example, this: @RequiredArgsConstructor(onConstructor = @__(@Inject))
will generate a constructor annotated with @Inject