①:添加JSR303规范坐标与Hibernate校验框架对应坐标
java<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> </dependency>
②:对Bean开启校验功能
java@Component @Data @ConfigurationProperties(prefix = "servers") @Validated public class ServerConfig { }
③:设置校验规则
java@Component @Data @ConfigurationProperties(prefix = "servers") @Validated public class ServerConfig { @Max(value = 400,message = "最大值不能超过400") private int port; }
小结: 1. 启用Bean属性校验 导入JSR303与Hibernate校验框架坐标
2.使用@Validated注解启用校验功能
3.使用具体校验规则规范数据校验格式