在Spring boot中可以通过@configurationProperties与@Validated注解进行数据格式校验;我们通过一个示例进行说明:

  • 我们现在有个类User,里面有两个属性email(邮箱)和password(密码)
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 + '\'' +
                '}';
    }
}
  • 我们在applicaton.properties中配置这两个属性;
#配置User类中的相关内容
user.email=1111
user.password=123456
  • 我们在User类中设置读取application.properties文件的注解

 

 

 此时我们运行下,发现可以正确读取到email和password的值;

 

 

  •  此时我们通过@@Validated注解给User类中的email属性加上校验。校验其必须为邮箱格式,此时我们运行下会报错。报错信息如下:

 

 

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
  • 我们将email的值调整成一个邮箱格式:

 

 我们在运行下此时的程序: