Spring:正确使用Lombok Builder

b4wnujal  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(86)

我在使用lombok @Builder时遇到了问题。
在SpringBoot应用程序中,我创建了以下组件:

@Getter
@Builder
@Component
@AllArgsConstructor
public class ContentDTO {
    private UUID uuid;
    private ContentAction contentAction;
    private String payload;
}

字符串
但当我运行应用程序<我收到:

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阻止了豆的autowiring?
以及如何在Spring ApplicationContext中正确地使用lombok-builder?

mqkwyuun

mqkwyuun1#

builder的使用需要一个默认的构造函数,当你添加**@AllArgsConstructorannotation的时候出现了问题,所以你必须同时添加@NoArgsConstructor**annotation,这应该是你代码的解决方案。

jaql4c8m

jaql4c8m2#

好吧,ContentDTO@Component注解,因此 Spring 试图拾取并注册ContentDTO的示例,以便这样做它试图使用由 Lombock 生成的所有args构造函数创建一个示例,因为它是唯一可用的构造函数。
失败是因为找不到ContentDTO构造函数期望的具有给定类型的注册bean。
添加@NoArgsConstructor或默认构造函数而不带参数,就像你做的那样,将工作,生成器是不相关的。

相关问题