有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当注释bean用作另一个bean中的集合时,java自定义约束验证器不工作

我使用SpringBoot创建rest服务,为了验证我的DTO,我使用java验证api

在某些DTO中,我必须进行跨域验证,因此我使用自定义验证程序

在我的DTO中,我必须检查重量重量单位是否都存在或都不存在。如果其中只有一个存在,那么我必须抛出验证错误

如果我在另一个DTO中直接使用这个DTO,它会非常有效,但当我将它用作DTO的集合时,它会失败。它抛出org。springframework。豆。InvalidPropertyException

自定义验证器

@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());
    }
}

应用验证程序的Bean

@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
}

将此bean用作集合的其他bean

public class ProductListDTO extends BaseDTO {

    @Valid
    private List<ProductDTO> products = new ArrayList<>(0);

    //getters and setters

}

现在,当我在请求中只传递权重或权重单位时,它抛出异常bean类[com.inventory.DTO.ProductListDTO]的无效属性“products[]”:属性路径“products[]”中的无效索引。


共 (0) 个答案