首先要使用jsr303数据校验,要先导入依赖
<!--JSR303数据校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
| @Null | 被注释的元素必须为null |
|---|---|
| @NotNull | 被注释的元素必须不为null |
| @AssertTrue | 被注释的元素必须为true |
| @AssertFalse | 被注释的元素必须为false |
| @Min(value) | 被注释的元素必须是一个数字, 其值必须大于等于指定的最小值 |
| @Max(value) | 被注释的元素必须是一个数字, 其值必须小于等于指定的最大值 |
| @Dec imalMin(value) | 被注释的元素必须是一个数字, 其值必须大于等于指定的最小值 |
| @Dec imalMax (value) | 被注释的元素必须是一个数字, 其值必须小于等于指定的最大值 |
| @Size(max,min) | 被注释的元素的大小必须在指定的范围内 |
| @Digits (integer, fraction) | 被注释的元素必须是一个数字, 其值必须在可接受的范围内 |
| @Past | 被注释的元素必须是一个过去的日期 |
| @Future | 被注释的元素必须是- -个将来的日期 |
| @Pattern(value) | 被注释的元素必须符合指定的正则表达式 |
| 被注释的元素必须是电子邮箱地址 | |
| @Length | 被注释的字符串的大小必须在指定的范围内 |
| @NotEmpty | 被注释的字符串的必须非空 |
| @Range | 被注释的元素必须在合适的范围内 |
下边看一个例子
package com.zkw.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Repository;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
@Data
@Repository
@Validated
@ConfigurationProperties(prefix = "dog")
public class Dog {
@Email(message = "邮箱格式错误")
private String name;
private int age;
}
dog:
name: 大黄
age: 3
测试
package com.zkw;
import com.zkw.pojo.Dog;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot01HelloworldApplicationTests {
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
}
结果如下

664

被折叠的 条评论
为什么被折叠?



