首页 > 解决方案 > SpringBoot 应用程序中没有可用的“java.util.UUID”类型的限定 bean

问题描述

我正在使用 SpringBoot 来创建应用程序。

应用程序包中的组件之一是:

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

在测试包中,我创建了用于创建 tets-data 的 utils-class:

 @Component
 public class TestData {

     private UUID uuid = null;
     private final ContentAction contentAction = ContentAction.valueOf("SEND_NEW");
     private final String payload = "New message";
     private ContentDTO contentDTO;

     public TestData() {
       contentDTO = 
   ContentDTO.builder().uuid(uuid).contentAction(contentAction).payload(payload).build();     
  }

    public ContentDTO getContentDTO() {
        return contentDTO;
     }
 }

和测试类:

 @RunWith(SpringRunner.class)
 @SpringBootTest(classes = {InfoDiodeSinkApplication.class, ContentDTO.class, TestData.class})
 public class InfoDiodeSinkApplicationTest {

 @Autowired
 private InfoDiodeSinkApplication infoDiodeSinkApplication;
 @Autowired
 private ContentDTO contentDTO;
 @Autowired
 private TestData testData;

 public void contextLoads() {
 }

 @Test(expected = Exception.class)
 public void testDtoHandler() {
     contentDTO = testData.getContentDTO();
     Mockito.doThrow(new 
       EOFException()).when(infoDiodeSinkApplication).dtoHandler(contentDTO);
   }
 }

但是当我运行测试时,我收到:

   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    

但是 java.util.UUID 包含在标准 java-lib 中。而且我认为 SpringBoot 能够为来自标准库的所有 bean 创建默认配置。

我是否理解正确,Spring 建议我为标准 UUID 创建自定义 bean 配置?我做错了什么?

标签: spring-bootjavabeansautowiredapplicationcontext

解决方案


问题在于使用 lombock-@Builder。我在自定义生成器上更改了 lombock-builder,问题消失了

 @Getter
 @Component
 public class ContentDTO {

  private ContentDTO() {
      // private constructor
   }

   private UUID uuid;
   private ContentAction contentAction;
   private String payload;

   public static Builder newBuilder() {
       return new ContentDTO().new Builder();
  }

  public class Builder{
      private Builder() {
          // private constructor
      }

    public Builder uuid(UUID uuid) {
        ContentDTO.this.uuid = uuid;
        return this;
    }

    public Builder contentAction(ContentAction contentAction) {
        ContentDTO.this.contentAction = contentAction;
        return this;
    }

    public Builder payload(String payload) {
        ContentDTO.this.payload = payload;
        return this;
    }

    public ContentDTO build() {
        return ContentDTO.this;
      }
    
    }

 }

推荐阅读