Java 当注释bean用作另一个bean中的集合时,自定义约束验证器不工作
我使用SpringBoot创建rest服务,为了验证我的DTO,我使用java验证api 在某些DTO中,我必须进行跨域验证,因此我使用自定义验证程序 在我的DTO中,我必须检查重量和重量单位是否都存在或都不存在。如果其中只有一个存在,那么我必须抛出验证错误 如果我在另一个DTO中直接使用这个DTO,它会非常有效,但当我将它用作DTO的集合时,它会失败。它抛出org.springframework.beans.InvalidPropertyException 自定义验证器 将此bean用作集合的其他beanJava 当注释bean用作另一个bean中的集合时,自定义约束验证器不工作,java,spring,validation,Java,Spring,Validation,我使用SpringBoot创建rest服务,为了验证我的DTO,我使用java验证api 在某些DTO中,我必须进行跨域验证,因此我使用自定义验证程序 在我的DTO中,我必须检查重量和重量单位是否都存在或都不存在。如果其中只有一个存在,那么我必须抛出验证错误 如果我在另一个DTO中直接使用这个DTO,它会非常有效,但当我将它用作DTO的集合时,它会失败。它抛出org.springframework.beans.InvalidPropertyException 自定义验证器 将此bean用作集合
公共类ProductListDTO扩展BaseDTO{
@有效的
私有列表产品=新的ArrayList(0);
//接球手和接球手
}
现在,当我在请求中只传递weight或weight_unit时,它抛出bean类[com.inventory.DTO.ProductListDTO]的异常无效属性“products[]”:属性路径“products[]”中的无效索引。如果在ProductListDTO中使用数组而不是列表会怎么样?它与数组一起工作,但这是唯一的方法吗?请参见“包含在何处构造ProductListDTO对象”我不构造它,它在控制器中使用&作为请求体出现
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { ProductWeightValidatorImpl.class })
public @interface ProductWeightValidator {
String message() default "{com.inventory.validator.ProductWeightValidator.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class ProductWeightValidatorImpl implements ConstraintValidator<ProductWeightValidator, ProductDTO> {
@Override
public void initialize(ProductWeightValidator constraintAnnotation) {
}
@Override
public boolean isValid(ProductDTO product, ConstraintValidatorContext context) {
return Objects.nonNull(product.getWeight()) && StringUtil.nullOrEmpty(product.getWeightUnit()) || Objects.isNull(product.getWeight()) && StringUtil.nonNullNonEmpty(product.getWeightUnit());
}
}
@ProductWeightValidator(message = "weight and weight_unit must be provided together")
public class ProductDTO extends BaseDTO {
// other fields
private Double weight;
@JsonProperty("weight_unit")
private String weightUnit;
//getters and setters
}
public class ProductListDTO extends BaseDTO {
@Valid
private List<ProductDTO> products = new ArrayList<>(0);
//getters and setters
}