青岛做网站需要多少钱,怎么做网站的排名,搭建网站要哪些知识,wordpress 5.0.3文章编辑JSR是 Java EE 的一种标准#xff0c;用于基于注解的对象数据验证。在Spring Boot应用中#xff0c;你可以通过添加注解直接在POJO类中声明验证规则。这样可以确保在使用这些对象进行操作之前#xff0c;它们满足业务规则。个人认为非常有用的#xff0c;因为它减少了代码中… JSR是 Java EE 的一种标准用于基于注解的对象数据验证。在Spring Boot应用中你可以通过添加注解直接在POJO类中声明验证规则。这样可以确保在使用这些对象进行操作之前它们满足业务规则。个人认为非常有用的因为它减少了代码中的校验逻辑使得校验逻辑更加集中且易于管理。 以我上一篇中YAML配置为例我们可以创建一个配置类 Person其中包括内嵌的 Dog 类并使用JSR 303注解来验证输入数据
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.validation.annotation.Validated;Validated
public class Person {NotBlank(message Name cannot be empty)private String name;Min(value 18, message Age must be at least 18)private int age;NotBlank(message UUID cannot be empty)private String uuid;NotNull(message Dog cannot be null)private Dog dog;// Standard getters and setterspublic static class Dog {NotBlank(message Dogs name cannot be empty)private String name;NotBlank(message Breed cannot be empty)private String breed;// Standard getters and setters}
}在这个例子中 NotBlank用于确保字符串类型的字段不是 null且去除前后空白字符后长度大于0。 Min 用来确保数值字段如年龄满足最小值要求。 NotNull确保对象字段如 Dog不是 null。 这些验证注解将在对象绑定后自动应用例如当从HTTP请求中接收数据并绑定到这些对象时或者通过Spring的配置属性绑定机制从配置文件如YAML加载数据时。要启用这种验证需要确保已经在Spring Boot项目中包括了 Spring 的 ValidationAPI 和其实现库例如 Hibernate Validator。
!-- 添加依赖到 pom.xml --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-validation/artifactId
/dependency总结: 当Spring创建这个 Person类的实例并注入配置值时如果配置值不符合这些验证条件将抛出异常可以通过适当的异常处理显示错误信息或采取其他错误处理措施。