spring boot 中使用 Hibernate validate 进行入参字段校验,一般用于web 接口入参校验,用起来非常方便。
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;
}
}
使用步骤:
@Validated
public class NewsInfoController {
/**
* Method: 添加新闻
* Description:
* Author: pan ying
* Date: 2018/6/13 17:43
*
* @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;
}
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;
}