20

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?

2
  • Why don't you just test it? If it works, then it's legit (probably some spring magic to match the constructor parameters with the fields to get the appropriate annotations). However, I assume it won't, then you have to put @Lazy to lombok.copyableAnnotations.
    – Jan Rieke
    Commented Dec 28, 2019 at 12:09
  • I tested but I’m not sure about the results. That’s why I’m here trying to find out the correct way of doing that
    – blackjack
    Commented Dec 28, 2019 at 12:12

3 Answers 3

36

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.

21

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;
}
1
5

You can use:

@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class A {
  private final B b;

  //or use this
  //@Lazy
  //private final B b;
}
2
  • What is the role of underscore after onConstructor? The property name on annotation definition is onConstructor and not onConstructor_, I've never seen such a construction before, the documentation only denotes note the underscore after onConstructor without denoting for what actually it is
    – bladekp
    Commented Oct 20, 2023 at 10:12
  • @bladekp the strange syntax is explained in the JavaDoc for the various Lombok annotations. For example, @AllArgsConstructor. Some more explanation of the gory details is in the Small Print here.
    – E-Riz
    Commented Apr 25 at 17:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.