Spring Boot Validation 详细使用教程
在现代Web开发中,数据验证是确保应用程序健壮性和安全性的关键环节。本文将深入探讨Spring Boot中Validation的使用方法,从基础概念到实际应用,为您提供一份完整的学习指南。
🎯 一、Validation的作用与价值
什么是Validation?
Validation(数据验证) 是确保应用程序接收到的数据符合预期格式和业务规则的过程。在Web应用中,数据验证是第一道防线,可以有效防止:
- 🛡️ 恶意攻击:SQL注入、XSS攻击等
- 🚫 数据污染:不符合格式的数据进入数据库
- 💥 系统崩溃:由于非法数据导致的运行时异常
- 🐛 业务逻辑错误:不符合业务规则的数据处理
Spring Boot Validation的优势
Spring Boot集成了**Bean Validation (JSR-303/JSR-380)**标准,提供了:
- ✅ 注解驱动:简洁的注解方式定义验证规则
- 🔧 灵活配置:支持自定义验证器和错误消息
- 🌐 国际化支持:多语言错误消息
- 🏗️ 无缝集成:与Spring MVC完美结合
官方资源
- Bean Validation官网:https://beanvalidation.org/
- Hibernate Validator文档:https://hibernate.org/validator/
- Spring Boot官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.validation
📋 二、Validation注解详解
Spring Boot Validation提供了丰富的验证注解,以下是常用注解的详细说明:
2.1 空值验证注解
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@NotNull |
验证对象不为null | 任何类型 | @NotNull Long id |
@NotEmpty |
验证集合/数组/字符串不为null且不为空 | String, Collection, Map, Array | @NotEmpty String name |
@NotBlank |
验证字符串不为null且去空格后不为空 | String | @NotBlank String username |
2.2 长度和大小验证
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@Size(min, max) |
验证字符串长度或集合大小 | String, Collection, Map, Array | @Size(min=2, max=20) String name |
@Length(min, max) |
验证字符串长度(Hibernate扩展) | String | @Length(min=6, max=18) String password |
2.3 数值验证注解
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@Min(value) |
验证数值不小于指定值 | Number及其子类 | @Min(18) Integer age |
@Max(value) |
验证数值不大于指定值 | Number及其子类 | @Max(120) Integer age |
@DecimalMin |
验证decimal不小于指定值 | BigDecimal, String | @DecimalMin("0.0") BigDecimal price |
@DecimalMax |
验证decimal不大于指定值 | BigDecimal, String | @DecimalMax("999.99") BigDecimal price |
@Digits(integer, fraction) |
验证数字的整数位和小数位数 | Number及其子类 | @Digits(integer=3, fraction=2) BigDecimal amount |
2.4 格式验证注解
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@Pattern(regexp) |
验证字符串匹配正则表达式 | String | @Pattern(regexp="^1[3-9]\\d{9}$") String phone |
@Email |
验证邮箱格式 | String | @Email String email |
2.5 日期时间验证
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@Past |
验证日期是过去时间 | Date, Calendar, LocalDate等 | @Past LocalDate birthday |
@Future |
验证日期是将来时间 | Date, Calendar, LocalDate等 | @Future LocalDateTime appointmentTime |
@PastOrPresent |
验证日期是过去或现在 | Date, Calendar, LocalDate等 | @PastOrPresent LocalDate createTime |
@FutureOrPresent |
验证日期是将来或现在 | Date, Calendar, LocalDate等 | @FutureOrPresent LocalDate deadline |
2.6 布尔验证
| 注解 | 作用 | 适用类型 | 示例 |
|---|---|---|---|
@AssertTrue |
验证boolean值为true | boolean, Boolean | @AssertTrue Boolean accepted |
@AssertFalse |
验证boolean值为false | boolean, Boolean | @AssertFalse Boolean deleted |
2.7 自定义验证注解
除了使用标准的验证注解外,我们还可以创建自定义的验证注解来满足特定的业务需求。
为什么需要自定义验证注解?
- 复杂业务规则:标准注解无法满足复杂的业务验证逻辑
- 跨字段验证:需要同时验证多个字段的关联性
- 代码复用:将常用的验证逻辑封装成注解,提高代码复用性
- 语义清晰:自定义注解名称更能体现业务含义
自定义验证注解的组成
一个完整的自定义验证注解包含两部分:
- 注解定义:定义注解的属性和元数据
- 验证器实现:具体的验证逻辑实现
创建步骤
步骤1:定义注解
@Documented
@Constraint(validatedBy = PasswordMatchesValidator.class) // 指定验证器
@Target({
ElementType.TYPE}) // 可以应用在类上
@Retention(RetentionPolicy.RUNTIME) // 运行时保留
public @interface PasswordMatches {
String message() default "密码和确认密码不匹配"; // 默认错误消息
Class<?>[] groups() default {
}; // 验证分组
Class<? extends Payload>[] payload() default {
}; // 负载信息
}
步骤2:实现验证器
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {
@Override
public void initialize(PasswordMatches constraintAnnotation) {
// 初始化方法,可以获取注解参数
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
// 实现具体的验证逻辑
if (obj instanceof UserCreateDto) {
UserCreateDto userDto = (UserCreateDto) obj;
String password = userDto.getPassword();
String confirmPassword = userDto.getConfirmPassword();
// 验证密码是否匹配
return password != null && password.equals(confirmPassword);
}
return true;
}
}
步骤3:使用自定义注解
@Data
@PasswordMatches // 应用自定义验证注解
public class UserCreateDto {
private String password;
private String confirmPassword;
// 其他字段...
}
🏗️ 三、Spring Boot项目搭建(JDK 1.8)
3.1 Maven依赖配置
创建一个基于JDK 1.8的Spring Boot项目,pom.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>validation-demo</artifactId>
<version>1.0.0</version>
<name>Spring Boot Validation Demo</name>
<description>Spring Boot Validation详细使用教程示例</description>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Validation Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring Boot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2 application.yml配置
server:
port: 8080
spring:
application:
name: validation-demo
# 日志配置
logging:
level:
com.example.validation: DEBUG
org.springframework.web: DEBUG
💻 四、详细使用代码示例
4.1 创建用户实体类
package com.example.validation.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 用户实体类 - 展示各种验证注解的使用
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
/**
* 用户名验证:
* - 不能为空
* - 长度2-20字符
* - 只能包含字母、数字、下划线
*/
@NotBlank(message = "用户名不能为空")
@Length(min = 2, max = 20, message = "用户名长度必须在2-20个字符之间")
@Pattern(regexp = "^[a-zA-Z0-9_]+$", message = "用户名只能包含字母、数字和下划线")
private String username;
/**
* 密码验证:
* - 不能为空
* - 最少6位
* - 必须包含字母和数字
*/
@NotBlank(message = "密码不能为空")
@Size(min = 6, message = "密码长度不能少于6位")
@Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d).+$", message = "密码必须包含字母和数字")
private String password;
/**
* 邮箱验证
*/
@NotBlank(message = "邮箱不能为空"


1400

被折叠的 条评论
为什么被折叠?



