DEV Community

Composite
Composite

Posted on • Updated on

Are you using Lombok? Your classes don't need constructor with parameter Annotation.

Are you thought how to solve it with lombok?

@Service
public class SomeService {
  private final OtherService otherService;

  public SomeService (@Lazy OtherService otherService) {
    this.otherService = otherService;
  }
}
Enter fullscreen mode Exit fullscreen mode

I want use lombok like this:

@Service
@RequiredArgsConstructor
public class SomeService {
  @Lazy private final OtherService otherService;
}
Enter fullscreen mode Exit fullscreen mode

but @Lazy annotation won't work. lombok will marked as just a field annotation.
but I found this answer and it helped a lot:

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?

Yes. create lombok.config in your project root, and add this line.

lombok.copyableAnnotations += org.springframework.context.annotation.Lazy
Enter fullscreen mode Exit fullscreen mode

or, copy this line and bind another annotation such as @Value, @Qualifier or you want. (note: use full annotation signature!)

And, don't worry about annotation working and use lombok!

@Service
@RequiredArgsConstructor
public class SomeService {
  @Lazy private final OtherService otherService;
}
Enter fullscreen mode Exit fullscreen mode

Then lombok will processed like this:

@Service
public class SomeService {
  // 30 Sep, 2021: Annotation still remains because of copyableAnnotations.
  @Lazy private final OtherService otherService;

  public SomeService (@Lazy OtherService otherService) {
    this.otherService = otherService;
  }
}
Enter fullscreen mode Exit fullscreen mode

Gotcha!
Happy Coding!

Top comments (0)