解决方案
JSR-303 实现方案+JSR-349Bean 验证
JSR-303的实现使用hibernate的实现 @Valid注解
JSR-349Bean 验证的实现使用spring提供的@Validated注解
校验案例
本案例的环境为,springboot2.0.5.RELEASE
基础代码实现:
导入坐标
1
2
3
4<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>此坐标包含了@Valid 和@Validated
创建入口启动类
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
26package com.healthengine.department;
import com.healthengine.medpro.common.utils.IdWorker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
()
"com.healthengine.department") (
"com.healthengine.medpro.department") (
"com.healthengine.department.dao") (basePackages =
public class DepartmentApplication {
public static void main(String[] args){
SpringApplication.run(DepartmentApplication.class,args);
}
//雪花算法用来生成id
public IdWorker idWorker(){
return new IdWorker(1,1);
}
}注意:此入口启动类要放在Controller包的同级目录下,因为@SpringBootApplication注解会扫描同级目录及其子目录。此类只放在java目录下是不对的。要放在Java目录下的下级目录下
(正确目录格式)
(错误目录格式)
配置文件设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14server:
port: 9002
spring:
application:
name: medpro-department
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/medprotwo
username: xxxx
password: xxxx
jpa:
database: mysql
show-sql: true
open-in-view: true创建controller
案例使用到的java Bean
1 | package com.healthengine.medpro.company; |
1 | package com.healthengine.medpro.department; |
1 | package com.healthengine.medpro.company; |
基础校验(快速尝鲜)
1 | //对象参数校验 |
单个参数校验
在类中加入@Validated
1
2
3
4()
"/validation") (
public class ValidationTest {方法上对参数使用校验注解
1
2
3
4"/test2") (
public Result test2(@NotNull(message = "年齡不能為空") Integer age){
return new Result(ResultCode.SUCCESS);
}分组校验
创建分组标识接口
1
2public interface AddDepartment {
}在要校验的字段上使用校验注解并添加groups属性
1
2"用户名不能为空!",groups = {AddDepartment.class}) (message =
private String name;在方法上使用校验
1
2
3
4"/test3") (
public Result test3(@Validated(AddDepartment.class) @RequestBody Company company){
return new Result(ResultCode.SUCCESS);
}嵌套属性校验
在要需要嵌套校验的对象上添加@valid
1
2
3
4
5
6/**
* 部门列表
*/
//开启嵌套校验
"部门列表不能为空!") (groups = {AddDepartment.class},message =
private List<Department> departmentList;在方法上使用
1
2
3
4"/test4") (
public Result test4(@Valid @Validated(AddDepartment.class) @RequestBody Company company){
return new Result(ResultCode.SUCCESS);
}非嵌套属性校验
1 | "/test4") ( |
自定义校验规则
校验异常类全局处理
1 | package com.healthengine.department.exception; |
案例后发现的缺陷
使用hibernate参数校验注解后发现,使用Spring jpa 存入数据时也会产生校验。
目前解决方案,使用注解时为其分组。这样可以解决存入数据库时的校验,当存入数据库前,想做校验需要自己手动编写逻辑。