hibernate-validator 在我的 Spring Boot 项目的服务层中不起作用。
我的域模型:
@Data
public class IssueAttachmentDto extends AttachmentDto {
@NotEmpty
private String issueId;
}
@Data
public class AttachmentDto {
/**
* Only allow digit 1~5
*/
@NotEmpty
@Pattern(regexp = "\\b[1-5]\\b")
private String attachmentType;
@NotEmpty
@Valid
private FileDto fileDto;
}
@Data
public class FileDto extends BaseDto {
@NotEmpty
private String fileType;
/**
* Only allow positive integer
*/
@NotEmpty
@Pattern(regexp = "^[0-9]*[1-9][0-9]*$")
private Long fileSize;
@NotEmpty
private String fileKey;
@NotEmpty
private String fileName;
}
我的服务类别:
@Slf4j
@Service
@Validated
public class AttachmentServiceImpl implements AttachmentService {
@Override
public void uploadAttachment(IssueAttachmentDto issueAttachmentDto) {
try {
checkUploadAttachmentArgument(issueAttachmentDto);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
// something else...
}
private void checkUploadAttachmentArgument(@Valid IssueAttachmentDto issueAttachmentDto) {
// something else
}
}
我的配置类:
@Configuration
public class ConversionConfig {
@Bean
public ConversionService conversionService() {
return new DefaultConversionService();
}
}
无论我传递什么,方法 checkUploadAttachmentArgument(@Valid IssueAttachmentDto issuesAttachmentDto)
都不会抛出异常。在我看来,当我传递非法数据时,它会抛出 ConstraintViolationException 。我的代码或配置有什么问题,请帮助我。
最佳答案
Spring 无法代理私有(private)方法 - 这就是为什么当无效对象作为参数传递时您看不到抛出任何异常的原因。
只需将 @Valid
注释移至 uploadAttachment
方法参数,它就应该按预期工作。它应该看起来像这样:
public void uploadAttachment(@Valid IssueAttachmentDto issueAttachmentDto) {
// actual upload attachent logic
}
编辑:
即使 Spring 可以代理私有(private)方法,它也不会在您的情况下验证带注释的参数,因为您实际上是在原始类的实例上调用 checkUploadAttachmentArgument
,而不是另外执行验证的代理。
关于java - 验证不在服务层执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57836250/