Springboot's loose binding and JSR303 data verification

loosely bound

The last-name in the yaml file in spring boot can be bound to the lastName in the code. That is to say, the "-n" in last-name can be regarded as the capital letter "N" in lastName. This is Loosely bound.

code


// yaml文件
person:
  last-name: chen
  age: 3
  happy: false
  birth: 2002/12/2
  maps: {k1: v1,k2: v2}
  lists:
    - basketball
    - girl
    - music
  dog:
    name: 旺财
    age: 3
//正式代码
private String lastName;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

//--------------------------------
last-name ==== lastName

JSR303 data validation

  • It is a data verification format that is bound to the class @Validatedand uses specified parameters on the properties, such as @Email(message="邮箱格式错误")

  • Common data verification parameters, the package isjavax.validation.constraints

  • If an error is displayed when @Email is displayed, the corresponding dependency spring-boot-starter-validation needs to be imported into the pom.xml file. 

Just import dependencies

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

test

// JSR303常用校验	
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;

// 空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
// Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
    
// 长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) string is between min and max included.

// 日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

Guess you like

Origin blog.csdn.net/m0_52991090/article/details/121322828