JSR303提供规范,其余框架实现规范。

  1. 添加JSR303规范,在SpringBoot中不用给出版本号
<dependency>
	<groupId>javax.validation</groupId>
	<artifactId>validation-api</artifactId>
</dependency>
  1. 添加实现技术
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

在需要校验的Bean上开启校验功能@Validated,然后使用JSR303规范中的注解去定义校验规则就好了。

@Data
@Component
@ConfigurationProperties(prefix = "my-server")
@Validated
public class DataSourceConfigBean {
    private String url;

    @Max(value = 5000, message = "最大不能超过5000")
    @Min(value = 500, message = "最小不能低于500")
    private int timeout;
}

当属性注入时,就会进行属性校验,测试一下

Bean属性校验-LMLPHP

关于常用的校验规则有哪些?可以进入到JSR303注解包javax.validation.constraints下查看,这里给出一些常用的。

JSR303中常用的注解有:

06-21 17:09