Spring Validation是Spring框架中用于數據校驗的核心模塊,通過注解簡化數據校驗邏輯。
1. 依賴引入(SpringBoot項目)
Spring Boot項目:自動包含spring-boot-starter-validation
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2. 基本使用
在Spring MVC的Controller中使用@Valid和@Validated觸發校驗。
示例代碼:
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody @Valid User user, BindingResult result) {if (result.hasErrors()) {// 處理校驗錯誤return ResponseEntity.badRequest().body(result.getAllErrors());}// 保存用戶return ResponseEntity.ok(userService.save(user));
}
- @Valid:觸發校驗
- @Validated:Spring的擴展,支持分組校驗
- BindingResult:保存校驗結果,需緊跟被校驗參數
3. 常用校驗注解
以下是Bean Validation內置的校驗注解:
注解 | 說明 |
---|---|
@NotNull | 值不能為null |
@NotEmpty | 字符串/集合不能為空 |
@NotBlank | 字符串必須包含非空格字符 |
@Size(min, max) | 字符串/集合長度在范圍內 |
@Min(value) | 數字最小值 |
@Max(value) | 數字最大值 |
校驗郵箱格式 | |
@Pattern(regexp) | 正則表達式匹配 |
@Positive | 必須為正數 |
@Future | 日期必須是未來時間 |
示例實體類:
public class User {@NotBlank(message = "用戶名不能為空")private String username;@Size(min = 6, max = 20, message = "密碼長度需在6-20位")private String password;@Email(message = "郵箱格式不正確")private String email;// Getters and Setters
}
4.分組校驗
通過分組實現不同場景的差異化校驗規則。
定義分組接口:
public interface CreateGroup {}
public interface UpdateGroup {}
在實體中使用分組:
public class User {@Null(groups = CreateGroup.class, message = "創建時ID必須為空")@NotNull(groups = UpdateGroup.class, message = "更新時ID不能為空")private Long id;// 其他字段...
}
在Controller中指定分組:
@PostMapping("/users")
public ResponseEntity<?> createUser(@Validated(CreateGroup.class) @RequestBody User user) {// ...
}
5. 自定義校驗
步驟1:定義注解
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneValidator.class)
public @interface Phone {String message() default "手機號格式不正確";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};
}
步驟2:實現校驗邏輯
public class PhoneValidator implements ConstraintValidator<Phone, String> {@Overridepublic boolean isValid(String phone, ConstraintValidatorContext context) {return phone != null && phone.matches("^1[3-9]\\d{9}$");}
}
步驟3:使用自定義注解
public class User {@Phoneprivate String phone;
}