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

spring boot 的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

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 加上这个注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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;
}

实体类中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}