4
...
@RequiredArgsContructor(onConstructor_ = {@Lazy})
Class A{
  private final B b;
  @Lazy
  private final C c;
}
Class A{
  private final B b;
  private final C c;
  A(B b,@Lazy C c){
    this.b = b;
    this.c = c;
  }
}

Is it the same?

I want to use @Lazy with @RequiredArgsConstructor.

2 Answers 2

2

It's not the same. When you put @Lazy over constructor it leads to the creation of a lazy-resolution proxy for all affected dependencies, i.e. in your first case both b and c injected into constructor are resolved lazily.

In the second case only c is resolved lazily.

See Is using `@Lazy` on a component constructor equal to annotating every argument?

I want to using @Lazy with @RequiredArgsConstructor

Use your first approach.

P.S. Btw, having @Lazy over constructor in the first case makes redundant @Lazy over private final C c;.

Sign up to request clarification or add additional context in comments.

Comments

1

As @Sergey said, it's not the same, it affects all dependencies.

Referring to Mafor's answer:

You can configure Lombok to copy the @Lazy annotation from the field to the constructor's parameter.

Create lombok.config file in the project's root and add the following line:

lombok.copyableAnnotations += org.springframework.context.annotation.Lazy

Then you can define your class as follows:

@RequiredArgsContructor
Class A{
  private final B b;
  @Lazy
  private final C c;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.