SpringBoot中使用validation对类进行校验

环境: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就可以实现了

以上纯属个人见解,如有问题请联系本人!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值