Java 基于DTO级别的注释验证发生在字段级别验证之前,如@NotNull@Size等

Java 基于DTO级别的注释验证发生在字段级别验证之前,如@NotNull@Size等,java,spring-boot,hibernate-validator,spring-validator,Java,Spring Boot,Hibernate Validator,Spring Validator,我有一个DTO类,其中一些字段是必填的。 并且,基于另一个类型字段,其中值可以假定为A和B 如果是类型A,则只需检查1项即可通过,如果是B,则也可以超过1项 我需要检查列表在DTO类级别中是否至少有1个值。而且,在自定义注释验证中,我需要根据DTO的类型字段检查列表的大小 所以,在DTO中 @NotNull @Size(min = 1) private List<@NotBlank String> items; 但是,由于字段级别稍后发生,若我为items字段传递null,它将转到

我有一个DTO类,其中一些字段是必填的。 并且,基于另一个类型字段,其中值可以假定为A和B 如果是类型A,则只需检查1项即可通过,如果是B,则也可以超过1项

我需要检查列表在DTO类级别中是否至少有1个值。而且,在自定义注释验证中,我需要根据DTO的类型字段检查列表的大小

所以,在DTO中

@NotNull
@Size(min = 1)
private List<@NotBlank String> items;
但是,由于字段级别稍后发生,若我为items字段传递null,它将转到这个注释验证器&当字段为null时抛出NPE&我正在尝试获取大小

临时的解决方案是我做空检查,然后检查大小,但无论如何,在字段级别,我们给出了@NotNull

在字段级验证发生后,是否有任何方法进行类级自定义注释以进行验证。
在这种情况下,它将抛出字段级验证,因为字段为空&将不会转到自定义类级注释

您可以使用JS-303验证组(请参阅文档中的:

        if (cancelType == CancellationTypeEnum.A && cancelDto.getItems().size() > 1) {

            isValid = false;
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                    "Only one item can be sent for 'A' cancel type.").addConstraintViolation();

        } 
JSR-303的有效变体,支持验证规范 小组

例如:

@CheckEnumSize(groups = {Secondary.class})
public class CancelDto {

    public CancelDto(List<String> items) {
        this.items = items;
    }

    @NotNull(groups = {Primary.class})
    @Size(min = 1)
    public List<@NotNull String> items;

    public CancellationTypeEnum cancelType;

    public List<String> getItems() {
        return items;
    }
}
 
对于次级,也一样:

public interface Secondary {
}
最后,您可以按如下方式使用验证:

@Service
@Validated({Primary.class, Secondary.class})
public class CancelService {

    public void applyCancel(@Valid CancelDto cancel) {
        //TODO
    }

}
将上述代码与
CancelDto
一起使用时,如果项目为空,则应获得:

Caused by: javax.validation.ConstraintViolationException: applyCancel.cancel.items: must not be null
Caused by: javax.validation.ConstraintViolationException: applyCancel.cancel.items: must not be null