Search code examples
springlazy-loadinglombok

How to use @Lazy annotation in a class constructor with Lombok?


Given a class AnimalService:

public class AnimalService{

      private DogService dogService;

      private AnimalService(@Lazy DogService dogService){
          this.dogService = dogService;
      }
    }
}

In this case if I want to use Lombok annotations is there a way to keep the @Lazy loading?

The following code will do the same as the above code?

@AllArgsConstructor
public class AnimalService{
  @Lazy
  private DogService dogService;
}

@Lazy
public class DogService{
//code
}

Is this an appropriate way to use @Lazy annotation with Lombok?


Solution

  • If you want it only for a single class without doing a global Lombok config you can use the following snippet:

    @AllArgsConstructor(onConstructor = @__(@Lazy))
    public class AnimalService{
      @Lazy
      private DogService dogService;
    }