分组校验
在 Spring Boot 中,我们可以使用 Hibernate Validator 进行分组校验。这允许针对不同业务场景(如创建或更新)应用不同的规则。
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定义分组
public interface CreateGroup { }
public interface UpdateGroup { }
定义校验项时指定归属的分组
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class User {
@NotBlank(message = "姓名不能为空", groups = {UpdateGroup.class})
private String name;
@NotBlank(message = "用户名不能为空", groups = {CreateGroup.class, UpdateGroup.class})
@Size(min = 5, max = 20, message = "用户名长度必须在 5-20 个字符之间", groups = {CreateGroup.class, UpdateGroup.class})
private String username;
// getter 和 setter 方法省略...
}
校验时指定要校验的分组
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
{
String {
;
}
String {
;
}
}

















