环境:JDK1.8、MAVEN 3.6.1 、eclipse
1.当前的pom文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.22.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- junit配置 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
2.创建实体类
当前的
User
类中的内容:
/**
* @description 用户类,并添加校验规则
* @author hy
* @date 2019-08-13
*/
public class User {
@NotNull(message = "用户名不能为空!")
@Size(min = 1, max = 10, message = "用户名只能在1到10个字符之间!")
private String name;
@NotNull(message = "年齡不能空!")
@Min(value = 1, message = "最小值只能為1!")
@Max(value = 120, message = "最大值只能為120!")
private Integer age;
@NotNull(message = "密码不能为空!")
@Size(min = 6, max = 6, message = "密码只能是6位数!")
private String password;
......省略getter、setter和toString方法
}
3.编写入口类
当前
Application
类中的内容:
/**
* @description SpringBoot的验证功能
* @author hy
* @date 2019-08-13
*/
@RestController
@SpringBootApplication
public class Application {
@RequestMapping("/test")
public String test() {
return "【校验成功】";
}
@RequestMapping("/validate")
public String userValidate(@Validated User user) {
System.out.println(user);
return "【可以添加 " + user + "】";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.测试
基本上所使用的注解验证都成功了!
5.总结
1.当一个类需要被验证的时候可以使用@NotNull、@Size、@Min、@Max
等来限定当前字段,通过message
显示当前错误的原因
2.注意当前的需要校验的类不需要像spring官网一样
添加@Service 和@Validated
3.在需要校验的方法上使用该校验类前面添加@Validated
就可以实现了
以上纯属个人见解,如有问题请联系本人!