Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Lazy with @RequiredArgsConstructor

...
@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.

like image 997
Crazy Coke Avatar asked Sep 02 '25 10:09

Crazy Coke


1 Answers

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;.

like image 175
Sergey Tsypanov Avatar answered Sep 04 '25 04:09

Sergey Tsypanov