java - 验证不在服务层执行

标签 java spring-boot hibernate-validator

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/

相关文章:

javascript - Hibernate @email 验证失败

java - 二维数组打印每行第一个负数和最后一个负数之间的元素之和

java - 一个实体上的两个关系,jhipster

java - SpringBoot应用程序忽略HibernateValidator的xml配置

maven-2 - org.hibernate.validator.engine.ConfigurationImpl 的来源

java - 未从 AttributeConverter 内的属性获取值

java - 以秒为单位存储准确的音频位置是否安全?

java - 继承隐藏方法

java - 返回所有值的问题

java - 如何在 Spring Boot 中使用分页对存储库实体进行排序