spring boot 中使用 Hibernate Validate

spring boot 中使用 Hibernate validate 进行入参字段校验,一般用于web 接口入参校验,用起来非常方便。

spring boot 的配置

package com.reapal.openapi.web.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class ValidatorConfiguration {


    @Bean
    /**
     * Method:  开启快速返回
     * Description:
     *          如果参数校验有异常,直接抛异常,不会进入到 controller,使用全局异常拦截进行拦截
     * Author: liu kai
     * Date: 2018/7/12 17:33
     *
     * @param
     * @return org.springframework.validation.beanvalidation.MethodValidationPostProcessor
     */
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /**设置validator模式为快速失败返回*/
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    @Bean
 public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                .addProperty( "hibernate.validator.fail_fast", "true" )
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}

controller 中使用

使用步骤:

  1. 在 controller 类上 @Validated
  2. BindingResult result 这个不能省,必须要有,测试不加不行。
  3. @Valid 加上这个注解
@Validated
public class NewsInfoController {
/**
 *
 * @param newsRequestVo
 * @return com.reapal.openapi.web.vo.ResultVo
 */
@RequestMapping(value = "/save" ,method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public ResultVo saveNewsInfo(@RequestBody @Valid NewsRequestVo newsRequestVo, BindingResult result){
   ResultVo resultVo = new ResultVo();
   newsInfoBusiness.insert(newsRequestVo);
   return  resultVo;
}

实体类中使用

hibernate validate 中提供大量的校验方式,以注解的形式。具体 api 就不再赘述。

public class NewsInfo implements Serializable {
    private static final long serialVersionUID = 3148176768559230877L;
    

    /** id */
    private String id;
    /** 新闻编号 */
    private String newsNo;
    /** 标题 */
    @NotNull
    @Length(max=30, message="长度超过限制")
    private String title;
}

你可能感兴趣的:(spring boot 中使用 Hibernate Validate)