JSR303数据校验

Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。

导入依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

使用:

类上添加@validated、字段上根据实际情况使用。

例如邮件格式:

@Component
@ConfigurationProperties(prefix = "person")
@Validated  //数据校验
public class Person {

    @Email(message="邮箱格式错误")
    private String email;
    
    ......
      
}

在yml中给email字段赋非邮箱格式的值,如lihua,运行报错,并提示message中的消息:

Binding to target org.springframework.boot.context.properties.bind.BindException: 
Failed to bind properties under 'person' to com.hwl.swgger01.config.pojo.Person failed: Property: person.email Value: lihua Origin: class path resource [application.yml] - 4:10 Reason: 邮箱格式错误

其他现在方法一样。

 

posted @ 2021-10-03 19:23  四叶笔记  阅读(52)  评论(0编辑  收藏  举报