Spring 官方在 SpringBoot 文档中,关于参数校验(Validation)给出的解决方案是这样的:
The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (e.g. Hibernate validator) is on the classpath. This allows bean methods to be annotated with javax.validation constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the @Validated annotation at the type level for their methods to be searched for inline constraint annotations.
For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10
@Service
@Validated
public class MyBean {
public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code,
Author author) {
...
}
}
SpringBoot 文档
翻译一下就是使用 JSR-303 规范,直接利用注解进行参数校验。
PS:(JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是 Hibernate Validator)
实际体验- Java Bean对象中引入注解,这里我们先不对各个注解代表的含义展开解释。
@Data
@EqualsAndHashCode(callSuper = true)
public class Org extends baseEntity implements Serializable {
private static final long serialVersionUID = 6414776805478207026L;
@NotNull((message = "部门id不能为空" )
private Long id;
@NotBlank(groups = { Update.class })
@Size(max = 64, min = 1, groups = { Insert.class, Update.class })
private String orgName;
}
- 在Controller 层对应的方法上添加如下注解:
@Validated
public Result addOrg(@Validated(Insert.class) @RequestBody Org Org) {
..... do something
}
- 为什么要做参数验证?
- 防止恶意用户通过精心构造的参数破坏我们的系统
- 保证我们的业务有序进行
- 即便前端已经校验过,因为我们不能保证我们收到的请求都是由我们的前端程序发出
JSR303 规范默认提供了以下几种约束注解的定义。
上文我们已经基本了解如何使用以及各自代表的含义了,但是应该有人已经发现文中对应的校验注解上面添加了 groups 属性,并且在对应的 Controller 层 中使用 @Validated 指定使用了某个分组。下文我们将会学习如何添加参数校验分组以及如何自定义校验注解。



