Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
blackjack Avatar asked Dec 27 '19 19:12

blackjack


2 Answers

It won't work out of the box, but you can configure Lombok to copy the @Lazy annotation from the field to the constructor's parameter.

lombok.config

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

The lombok.config should be placed in the project's root or src folder.

like image 163
Mafor Avatar answered Nov 19 '22 05:11

Mafor


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;
}
like image 36
Daniel Olszewski Avatar answered Nov 19 '22 04:11

Daniel Olszewski