Bean验证`isValid`方法参数始终为null

时间:2018-09-20 05:32:15

标签: java bean-validation

我已经调试了几个小时的代码,但看不到为什么isValid方法参数总是为空:

@Bindable
public class EntityLinkNameModel {

    @WithoutSpace(groups = { DraftValidationGroup.class,  PersistenceValidationGroup.class }, message = ValidationMessages.FIELD_WITH_WHITESPACE)
    private String linkName;

    public EntityLinkNameModel() {}

    public EntityLinkNameModel(String linkName) {
        setLinkName(linkName);
    }

    public String getLinkName() {
        return linkName;
    }

    public void setLinkName(String linkName) {
        this.linkName = linkName;
    }
}

对此的验证者是

public class WithoutSpaceValidator implements ConstraintValidator<WithoutSpace, String> {

    public void initialize(WithoutSpace constraintAnnotation) {
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        boolean hasWhiteSpace = false;
        if(object != null) { // Problem is here, String is always null
            for (char c : object.toCharArray()) {
                if (Character.isWhitespace(c)) {
                    hasWhiteSpace = true;
                }
            }
        }
        return object !=null && !hasWhiteSpace;
    }

}

但是,验证总是将模型字段值设为空

EntityLinkNameModel model = getModel();
Console.log(model.getLinkName()); // Output is the name, so clearly this is not null
Set<ConstraintViolation<EntityLinkNameModel>> violations = validator.validate(model, DraftValidationGroup.class, PersistenceValidationGroup.class);
if(violations.isEmpty()) {} // but this is not empty and log even shows the `linkName` field passed into the `isValid` method is null

这里可能是什么问题?

0 个答案:

没有答案