我在使用 lombok @Builder 时遇到问题。
在 SpringBoot 应用程序中,我创建以下组件:
@Getter
@Builder
@Component
@AllArgsConstructor
public class ContentDTO {
private UUID uuid;
private ContentAction contentAction;
private String payload;
}
但是当我运行应用程序时< I receive:
Error creating bean with name 'contentDTO': Unsatisfied dependency expressed through constructor parameter 0
原因:
No qualifying bean of type 'java.util.UUID' available: expected at least 1 bean which qualifies as autowire candidate
“手指向天空”,我将 lombok-builder 更改为自定义构建器,如下所示:
@Getter
@Component
public class ContentDTO {
private ContentDTO() {
}
// fields
public static Builder newBuilder() {
return new ContentDTO().new Builder();
}
public class Builder{
private Builder() {
private constructor
}
public ContentDTO build() {
return ContentDTO.this;
}
}
}
问题就消失了。
很好,但我显然不明白,出了什么问题!
为什么在这种情况下 lombok-builder 会阻止 bean 的自动装配?
以及如何在Spring ApplicationContext中正确使用lombok-builder?
构建器的使用需要默认的构造函数。当您添加 @AllArgsConstructor 注释时,就会出现问题。因此,您还必须添加 @NoArgsConstructor 注释。这应该是您的代码的解决方案。
嗯
ContentDTO
具有 @Component
注释,因此 Spring 尝试获取并注册 ContentDTO
的实例,以便这样做它尝试使用 Lombok 生成的所有参数构造函数创建一个实例,因为它是唯一可用的构造函数。
它失败了,因为它无法找到具有 ContentDTO 构造函数期望的给定类型的注册 bean。
像您一样添加
@NoArgsConstructor
或不带参数的默认构造函数将会起作用,构建器不相关。