Validation


Information resource:

SpringBoot Docs: 2.8.9. @ConfigurationProperties Validation

url: https://docs.spring.io/spring-boot/docs/2.3.12.RELEASE/reference/html/spring-boot-features.html#boot-features

Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:

每当使用 Spring 的 @Validated 注释时,Spring Boot 都会尝试验证 @ConfigurationProperties 类。 可以直接在配置类上使用 JSR-303 javax.validation 约束注释。 为此,请确保类路径上有一个兼容的 JSR-303 实现,然后向字段添加约束注释,如以下示例所示:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties { @NotNull
private InetAddress remoteAddress; // ... getters and setters }

You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.

还可以通过注释使用@Validated 创建配置属性的@Bean 方法来触发验证。

To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with @Valid. The following example builds on the preceding AcmeProperties example:

为确保始终为嵌套属性触发验证,即使未找到任何属性,也必须使用 @Valid 注释关联字段。 以下示例建立在前面的 AcmeProperties 示例之上:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties { @NotNull
private InetAddress remoteAddress; @Valid
private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty
public String username; // ... getters and setters
}
}

JSR-303 Validation


JSR-303 是Java EE的一个子规范,官方参考实现Hibernate Validator

JSR-303 是一个数据验证的规范,而Hibernate Validator则是实现了这一规范,可以使用注解的方式对Bean进行验证,它的内部已经定义好了一系列的限制注解,只需将需要的注解标注在需要验证的实体类的属性上或者是对应的get方法上即可

JSR-303常用校验规则

布尔检查

注解 描述
@AssertFalse 被标注的对象是否为False
@AssertTrue 被标注的对象是否为True

空值检查

注解 描述
@Null 验证被标注的对象是否为NULL
@NotNull 验证被标注的对象是否不为NULL
@NotBlank 验证字符串是否非空,trim()后不为"",长度大于0
@NotEmpty 验证被标注对象是否为非空

长度检查

注解 描述
@Length(min,max) 验证字符串长度是否在min,max范围内
@Size(min,max) 验证对象(Collection,String,Map,Array)是否在规定范围内

日期检查

注解 描述
@Past 验证时间对象的值是否在当前时间之前
@Future 验证时间对象的值是否在当前时间之后
@Pattern(regexp) 验证字符串是否符合指定的正则表达式

数值检查

注解 描述
@Email 验证被标注对象是否为邮箱格式,NULL值不验证
@Valid 关联对象是数组或集合时,对其元素进行校验
@Digits(integer,fraction) 验证字符串是否是符合指定格式的数字,integer整数精度,fraction小数精度
@Min 验证字符串是否是大于Min指定的最小值的数字
@Max 验证字符串是否是小于Max指定的最大值的数字
@Range(min,max) 验证元素是否在min,max范围内

使用Hibernate Validator的Demo

Demo的项目结构:

pom.xml

<!-- 使用的是hibernate validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>

User(Bean)

/**
* @Email 约束输入邮件的格式
* @NotBlank 指字符串使用trim()去掉前后空格后,不能够为空
*/
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User implements Serializable { @NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱非法")
private String userEmail; @NotBlank(message = "电话不能为空")
@Pattern(regexp = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$",message = "手机号非法")
private String userPhone;
}

UserController

/**
* 以POST请求为例
* @Validated 注释类
* @RequestBody 可传Javabean类型
* @RequestParam 传单个参数
* @Valid 修饰在Javabean类型前
*/
@RestController
@Validated
public class UserController { @RequestMapping(value = "/test",method = RequestMethod.POST)
public boolean test(@RequestBody @Valid User user){
return true;
} @RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(){
return "hello,world";
}
}

Rusult:Postman发个请求瞅瞅结果

  • 输入正确格式的邮箱和手机

  • 输入非法格式的邮箱

  • 输入非法格式的手机号码

最新文章

  1. 【转载】Mysql 查看连接数,状态
  2. jq 部分用法
  3. 不可或缺 Windows Native (3) - C 语言: 运算符,表达式,条件语句,循环语句,转向语句,空语句等
  4. Eclipse中新建WEB项目,JSP页面报错。
  5. CSS笔记(十四)CSS3之动画
  6. windows svn
  7. Source Insight 技巧总结
  8. 创建一个基本的 Win32 窗口
  9. JavaScript获取当前日期
  10. 漫谈“采样”(sampling)
  11. odoo11登录之后返回的session信息分析
  12. Html from 标签
  13. 【Linux】Jenkins+Git源码管理(三)
  14. fabric 安装
  15. 最新的 CocoaPods 的使用教程(一)
  16. android开发:Android 中自定义属性(attr.xml,TypedArray)的使用
  17. python之 序列与字典遍历
  18. Netty源码分析第6章(解码器)----&gt;第4节: 分隔符解码器
  19. Zabbix概术及基础介绍(一)
  20. Android系统示例分析之AndroidBeamDemo

热门文章

  1. 预训练语言模型的前世今生 - 从Word Embedding到BERT
  2. OpenGL学习笔记(五)变换
  3. JVM 常用监控工具
  4. vulnhub靶机-XXE Lab 1
  5. 图 邻接表 邻接矩阵 BFS生成树 DFS生成树
  6. Golang语言系列-05-数组和切片
  7. 超详细,自动化测试接入Jenkins+Sonar质量门禁实践
  8. NOIP 模拟 $32\; \rm Six$
  9. 题解 P3322 [SDOI2015]排序
  10. Unity遮罩之Mask、RectMask2D与Sprite Mask适用场景分析