自定义Bean验证不适用于多个bean类

时间:2017-11-21 11:50:20

标签: java validation javabeans

我尝试为我的REST API创建自定义bean验证,但由于某种原因," required = false"验证无效。

当我发送没有属性callPosition的JSON时,我得到以下错误。

{
    "codes": [
        "ValidateString.GSMPLMNRecordModel.transit.callPosition",
        "ValidateString.transit.callPosition",
        "ValidateString.callPosition",
        "ValidateString.java.lang.String",
        "ValidateString"
    ],
    "arguments": [
        {
            "codes": [
                "GSMPLMNRecordModel.transit.callPosition",
                "transit.callPosition"
            ],
            "arguments": null,
            "defaultMessage": "transit.callPosition",
            "code": "transit.callPosition"
        },
        [
            "A",
            "B",
            "C",
            "D"
        ]
    ],
    "defaultMessage": "{com.mycompany.asn.validator.ValidateString.message}",
    "objectName": "GSMPLMNRecordModel",
    "field": "transit.callPosition",
    "rejectedValue": null,
    "bindingFailure": false,
    "code": "ValidateString"
},

在我的模型中:

@JsonProperty(required = false)
@ValidateString(acceptedValues = {"A","B","C","D"})
private String callPosition;

The Annotaion:

@Documented
@Constraint(validatedBy = StringValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface ValidateString {
    String[] acceptedValues();

    String message() default "{com.mycompany.validator.ValidateString.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

验证者:

public class StringValidator implements ConstraintValidator<ValidateString, String> {

    private List<String> valueList;

    @Override
    public void initialize(ValidateString validateString) {
        valueList = new ArrayList<String>();
        for (String val : validateString.acceptedValues()) {
            valueList.add(val.toUpperCase());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return value != null && valueList.contains(value.toUpperCase());
    }
}

                                       .

有谁能告诉我这是什么问题?

1 个答案:

答案 0 :(得分:1)

所有代码看起来都不错。使用提供的代码,我已经使用它成功调用了验证器(使用Jersey):

@POST
public Response getTest(TestRest testRest) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<TestRest>> constraintViolations = validator.validate(testRest);
    System.out.println(constraintViolations.size());

    return Response.status(Response.Status.OK).entity(constraintViolations.size()).build();
}

希望这有帮助。