Bean Validation (JSR 380)
什么是Bean Validation
Bean Validation 是 Java 中用于验证对象属性的规范(JSR 380)。它通过在对象的字段上添加注解来定义验证规则,然后在运行时对这些规则进行检查。
在java中使用Bean Validation
-
添加 Maven 依赖:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency>
-
创建一个简单的 Java Bean 类:
import javax.validation.constraints.*; public class Person { @NotNull(message = "Name cannot be null") @Size(min = 2, max = 30, message = "Name must be between 2 and 30 characters") private String name; @Min(value = 18, message = "Age must be at least 18") private int age; @Email(message = "Email should be valid") private String email; // Getters and setters... }
-
使用 Validator 进行验证:
import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; public class ValidationExample { public static void main(String[] args) { // 创建 ValidatorFactory ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); // 创建一个 Person 对象 Person person = new Person(); person.setName("John"); person.setAge(25); person.setEmail("john@example.com"); // 进行验证 Set<ConstraintViolation<Person>> violations = validator.validate(person); // 打印验证结果 for (ConstraintViolation<Person> violation : violations) { System.out.println(violation.getMessage()); } // 关闭 ValidatorFactory factory.close(); } }
在springboot中使用Bean Validation
-
创建一个简单的 Person 类:
import javax.validation.constraints.Email; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Person { @NotNull(message = "Name cannot be null") @Size(min = 2, max = 30, message = "Name must be between 2 and 30 characters") private String name; @Min(value = 18, message = "Age must be at least 18") private int age; @Email(message = "Email should be valid") private String email; // Getters and setters... }
-
创建一个简单的 Controller
import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/person") @Validated // 启用方法级别的验证 public class PersonController { @PostMapping("/add") public String addPerson(@RequestBody @Valid Person person) { // 处理添加人员的逻辑 return "Person added successfully!"; } }
-
处理验证结果
如果请求参数不符合验证规则,Spring Boot 会返回一个包含详细错误信息的响应。
可以通过使用BindingResult
对象获取验证结果:import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/person") @Validated public class PersonController { @PostMapping("/add") public String addPerson(@RequestBody @Valid Person person, BindingResult result) { if (result.hasErrors()) { // 处理验证失败的情况,返回错误信息 return result.getAllErrors().toString(); } // 处理添加人员的逻辑 return "Person added successfully!"; } }