[英]How to use @Lazy annotation in a class constructor with Lombok?
Given a class AnimalService:给定一个 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?在这种情况下,如果我想使用 Lombok 注释,有没有办法保持 @Lazy 加载?
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?这是在 Lombok 中使用 @Lazy 注释的合适方法吗?
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 以将@Lazy
注释从字段复制到构造函数的参数。
lombok.config lombok.config
lombok.copyableAnnotations += org.springframework.context.annotation.Lazy
The lombok.config should be placed in the project's root or src folder. lombok.config应该放在项目的根目录或 src 文件夹中。
If you want it only for a single class without doing a global Lombok config you can use the following snippet:如果您只希望它用于单个类而不执行全局 Lombok 配置,则可以使用以下代码段:
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.