JSR-303数据检验
原创JSR-303数据校验
1、JSR-303数据校验简介
JSR是Java Specification Requests的缩写,意思是Java 规范提案
JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation
即,JSR 303,Bean Validation规范 ,为Bean验证定义了元数据模型和API.。默认的元数据模型是通过Annotations来描述的,但是也可以使用XML来重载或者扩展。
2、常用校验注解
3、使用
3.1 导入依赖
在 pom.xml
配置文件当中导入依赖
org.springframework.boot
spring-boot-starter-validation
3.2 添加注解
在实体类中使用JSR-303数据校验注解
@Validated //数据校验
实体类 Person
中添加注解 @Validated
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
//javaConfig 绑定配置文件的值 可以采取下面这种方式
//加载指定的配置文件
//@PropertySource(value = "classpath:application.properties")
public class Person {
// //SP EL表达式取出配置文件的值
// @Value("${name}")
@Email(message = "邮箱格式错误")
private String name;
private Integer age;
private Dog dog;
private Boolean happy;
private Date birth;
private List
l配置文件 application.yaml
。上面数据校验 规定的是将实体类中的name属性规定为 Email
形式,但是我这里故意将属性name的值不写成Email的形式,为了查看最后的错误提示
person:
name: li #我这里故意写错 到后面查看错误的提示
age: ${random.int}
happy: false
birth: 2019/11/02
maps: {k1: v1,k2: v2}
hello: happy
lists:
-code
-music
-gril
dog:
name: 旺财
age: 3
3.3 测试
测试类 Springboot01HelloWordApplicationTests
package com.kuang;
import com.kuang.pojo.Dog;
import com.kuang.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot01HelloWordApplicationTests {
//只要前面写了组件@Component,这里就可以实现自动注入了
@Autowired
// private Dog dog;
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果
看到错误的提示,是属性 name
的格式不是 Email
,所以说明使用KSR-303数据校验成功!
4、实战项目中用到实例
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除