简体   繁体   中英

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?

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.

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

You can use:

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

  //or use this
  //@Lazy
  //private final B b;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM