使用@Valid和@InitBinder进行Spring Rest验证

时间:2016-05-02 19:49:20

标签: spring-mvc bean-validation spring-rest spring-validator

我有一个Spring REST应用程序,我想利用@Valid注释来装饰可以验证简单@NotNull检查的bean字段。

public ResponseEntity<ExtAuthInquiryResponse> performExtAuthInq(@Valid @RequestBody ExtAuthInquiryRequest extAuthInquiryRequest)
像这样

 @NotBlank(message = "requestUniqueId cannot be blank..")
private String requestUniqueId;

除此之外,我想使用@initBinder进行更复杂的验证(例如基于一个字段的值,第二个字段是必需的)

 @InitBinder("extAuthInquiryRequest")
protected void initExtAuthInqRequestBinder(WebDataBinder binder) {
    binder.setValidator(extAuthInqValidator);
}

这是验证器实现(仅适用于条件验证案例)

@Override
public void validate(Object target, Errors e) {

    ExtAuthInquiryRequest p = (ExtAuthInquiryRequest) target;
    // Dont want to do this check here. Can be simply done in the bean using @NotNull checks
    ValidationUtils.rejectIfEmpty(e, "requestUniqueId", "requestUniqueId is empty");


    // this is a good candidate to be validated here
    if(StringUtils.isNotBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneType())){
        if(StringUtils.isBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneNumber())){
            e.rejectValue("personInfo.contactInfo.phoneNumber.phoneNumber", "phoneNumber is mandatory when phoneType is provided");
        }
    }
}

}

我在网上看过很多使用其中一个或另一个的例子。我尝试过两种方法,但是当我有@initBinder设置时,请求对象上的@valid注释不再受到尊重。

因为我不想在spring validator类中编写代码来进行简单的@NotNull检查。 有没有办法一起做两种方法。

1 个答案:

答案 0 :(得分:0)