在Spring boot中可以通过@configurationProperties与@Validated注解进行数据格式校验;我们通过一个示例进行说明:
package com.hai.bao.springboot02; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author :haibao.wang * @date :Created in 2019/8/31 17:36 * @description:JSR303数据校验样例 * @modified By: * @version: $ */ @Component @ConfigurationProperties(prefix = "user") public class User { private String email; private String password; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "email=‘" + email + ‘\‘‘ + ", password=‘" + password + ‘\‘‘ + ‘}‘; } }
#配置User类中的相关内容 user.email=1111 user.password=123456
此时我们运行下,发现可以正确读取到email和password的值;
Caused by: org.springframework.boot.context.properties.bind.validation.BindValidationException: Binding validation errors on user - Field error in object ‘user‘ on field ‘email‘: rejected value [1111]; codes [Email.user.email,Email.email,Email.java.lang.String,Email];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments [];
default message [email],[Ljavax.validation.constraints.Pattern$Flag;@7cd1ac19,.*]; default message [不是一个合法的电子邮件地址];
origin class path resource [application.properties]:13:12
我们在运行下此时的程序:
spring-boot学习三:运用@configurationProperties与@Validated进行JSR303数据格式校验
原文:https://www.cnblogs.com/haibaowang/p/11437648.html