SpringBoot参数校验

业务背景

服务分运营版和客户版, 其中有很多接口可以复用, 但是参数校验不一致. 比如运营需要跨账号操作, 那么账号ID是必填参数; 客户版只能操作当前账号的数据, 公司ID会从currentUser中获取。所以技术需求拆分为

  1. 接口公用
  2. 分组校验

实现

  1. 先定义分组
1
2
public interface Admin {
}
1
2
public interface Client {
}
  1. 校验对象
1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
public class User {

/**
* 仅运营版进行该参数校验
*/
@NotNull(groups = Admin.class)
private String name;

@Min(1)
@NotNull
private Integer age;
}
  1. 接口定义
1
2
3
4
5
6
7
@Validated
public interface ValidateService {

@PostMapping("/validated")
Object addUser(@RequestBody @Valid User user);

}
  1. 通用逻辑实现
1
2
3
4
5
6
7
public class CommonValidateService implements ValidateService {

@Override
public Object addUser(User user) {
return user;
}
}
  1. 运营版接口实现
1
2
3
4
5
6
7
8
9
10
@RestController
public class AdminValidateService extends CommonValidateService {

@PostMapping("/admin")
@Validated({Admin.class, Default.class})
@Override
public Object addUser(User user) {
return super.addUser(user);
}
}
  1. 客户版接口实现
1
2
3
4
@RestController
public class ClientValidateService extends CommonValidateService {

}
  1. 单元测试
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
@SpringBootTest
class EnhanceValidateApplicationTests {

@Resource
private AdminValidateService adminValidateService;
@Resource
private ClientValidateService clientValidateService;

/**
* javax.validation.ConstraintViolationException: addUser.arg0.name: 不能为null, addUser.arg0.age: 最小不能小于1
*/
@Test
void admin_test() {
User user = new User();
user.setAge(0);
Object o = adminValidateService.addUser(user);
System.out.println(o);
}

/**
* javax.validation.ConstraintViolationException: addUser.arg0.age: 最小不能小于1
*/
@Test
void client_test() {
User user = new User();
user.setAge(0);
Object o = clientValidateService.addUser(user);
System.out.println(o);
}

}