如何解决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 配置?我做错了什么?
解决方法
问题在于使用 lombok-@Builder。我在自定义构建器上更改了 lombok-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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。