项目中写逻辑时,为保证程序的健壮性,需要对各种参数进行判断,这就导致业务代码不只健壮,还十分臃肿。其实 SpringBoot 中已经提供了 Validation 参数验证框架,可以方便的对参数进行合法性校验。
1. Validation 介绍
Validation 是用于检查程序代码中参数的有效性的框架,作为 Spring 框架中的一个参数校验工具,集成在 spring-context 包中。
1.1 Validation 注解
Validation 包含了众多的注解来帮助对Java程序不同类型的参数进行校验,校验相关注解分布在spring-boot-starter-validation
依赖的 javax.validation.constraints
包中。
- @Null/@NotnULL,标注的字段必须为null/必须不为null
- @AssertFalse/@AssertTrue,标注字段可以为null,但不为null时必须为false/true
- @Email,标注的字段对应值必须为email格式
- @URL,标注的字段值必须是URL
- @Patten,标注的字段值必须符合定义的正则表达式
其他类似注解的使用可以查看javax.validation.constraints
包中定义注解信息。
1.2 @valid 和 @validated的区别
在实际使用 Validation 框架时,经常会对 @valid 和 @validated 注解的使用产生误解,在这里对比一下两个注解的异同。
- 当使用仅是注解字段属性并验证规范,@Validated 和 @Valid 注解的功能是相同的。
- Spring Validation 验证框架提供了 @Validated 注解对参数进行验证,符合Spring’s JSR-303规范;而 @Valid 注解是 javax 提供的,符合标准的JSR-303规范。
在注解的使用上,@Validated 注解可以用于类型、方法和参数上;而 @Valid 还可以用于属性之上。
1
2
3
4
5
6
7
|
//@Validated定义 @Target ({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}) @Retention (RetentionPolicy.RUNTIME) @Documented public @interface Validated { Class<?>[] value() default {}; } |
1
2
3
4
5
6
|
//@Valid定义 @Target ({ METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention (RUNTIME) @Documented public @interface Valid { } |
- @Validated 注解可以使用分组校验的功能,为同一个对象属性提供不同分组,并根据分组来校验属性参数;而 @Valid 注解不支持分组验证。
- @Valid 注解支持嵌套验证,当类的属性是一个复杂对象时,可以使用 @Valid 对该属性对象中的属性同时进行校验;@Validated 并不支持在属性上使用。
2. SpringBoot 中使用 Validator 校验参数
2.1 依赖引入
SpringBoot 中使用 Validator 无需单独引入,因为在 web 依赖包中已经存在,直接使用即可。
1
2
3
4
5
|
<!-- starter web --> < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > |
如果 SpringBoot 版本比较新,在 web 包中可能已不再包含 Validation 框架,本地使用SpringBoot 2.6.3 版本 web 依赖包已经不再包含。
或者
SpringBoot新版本虽然不在web包中包含,但也提供了start启动依赖提供相关功能,单独引入 Jar 包可以使用如下坐标信息:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-validation</ artifactId > </ dependency > |
另外,引入依赖时还可以引入 hibernate 提供的 validator框架包,不过使用时需要表明版本号信息。
1
2
3
4
5
|
< dependency > < groupId >org.hibernate</ groupId > < artifactId >hibernate-validator</ artifactId > < version >6.1.5.Final</ version > </ dependency > |
2.2 标注校验实体类
后端接收请求参数时,通常是使用 JavaBean 对象来接收参数信息,如果想要对实体类中的属性进行校验,则需要对属性使用校验相关的注解标注,并且实体对象必须定义 getter/setter方法,可以使用 lombok 的 @Data。
1
2
3
4
5
6
7
8
9
10
11
12
|
@Data public class Customer{ private Long id; @NotNull private String countryName; @NotNull private String countryCode; @Email private String email; @Valid private Customer parentCustomerInfo; } |
2.3 开启参数校验
2.3.1 简单参数校验
服务接口接收单个简单参数时,可以在方法参数中直接使用校验注解。
1
2
3
4
|
@PostMapping ( "/get" ) public ResultMap getCustomerInfo( @RequestParam ( "customerCode" ) @NotNull (message = "用户编码不可以为空!" ) String customerCode){ return ResultMapUtils().ok(); } |
单参数校验时,还需要在 controller 层控制器类中使用 @Validated 标注才会生效。
2.3.2 JavaBean 校验
在实体类中使用校验注解标注需要校验的字段后,还需要在请求层接收参数时开启参数校验,只需要在 controller 接口层的参数中使用 @Validated 标注,在接口接收到请求参数时会自动进行校验。
1
2
3
4
5
6
7
|
@Autowired private CustomerService customerService; @PostMapping ( "/execute" ) public ResultMap execute( @RequestBody @Validated GeneralDataRequest<CustomerRequest> generalDataRequest){ CustomerRequest request = generalDataRequest.getData(); return customerService.execute(request); } |
2.4 捕捉参数校验异常
使用 Validation 校验异常后,当参数发生异常时,会抛出 MethodArgumentNotValidException 类型的异常,为了程序报错更通俗易懂,可以定义全局异常来捕获该类型的异常,并统一返回结果信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@SLF4j @ControllerAdvice public class ExceptionConfig { /** * 参数校验异常 */ @ResponseBody @ExceptionHandler (value = MethodArgumentNotValidException. class ) public ResultMap argumentExceptionHandler(MethodArgumentNotValidException exception) { String message = exception.getBindingResult().getFieldError().getDefaultMessage(); log.info( "发生参数异常:{}" , message); return ResultMapUtils.resultError(ErrorCodeConstant.System.E100003, null , message); } } |
到此这篇关于SpringBoot 中使用 Validation 校验参数的文章就介绍到这了,更多相关SpringBoot Validation 校验参数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7067917323801198599