javax.validation 入门示例

下面通过简单示例介绍如何使用 javax.validation,注意,这里将采用纯 java,不依赖 Spring 等框架。

添加 Maven 依赖

项目 pom.xml 文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.huangxin</groupId>
    <artifactId>demo_validation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--jsr 303-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <!-- hibernate validator-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

创建实体&添加注解

为了验证方便,这里直接使用手动调用 API 的方式对 Bean 进行校验,后续将介绍 javax.validation 与 Spring、Spring Boot 等集成。

代码如下:

package com.hxstrive.validation;

import lombok.Builder;
import lombok.Data;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.Null;
import java.util.Set;

/**
 * 注解元素必须为null
 * @author hxstrive.com
 **/
@Data
@Builder
public class NullDemo {

    @Null(message = "名称必须为空")
    private String name;

    public static void main(String[] args) {
        NullDemo.builder().name("Tom").build().validator("case1"); // Fail
        NullDemo.builder().name("").build().validator("case2"); // Fail
        NullDemo.builder().name(null).build().validator("case3"); // OK
    }

    private void validator(String caseName) {
        validator(caseName, this);
    }

    private <T> void validator(String caseName, T obj) {
        // 手动调用 API 对定义了注解的字段进行校验
        Validator validator = Validation.byProvider(HibernateValidator.class).configure()
                .failFast(true).buildValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> set = validator.validate(obj);
        if (set.size() > 0) {
            // 校验失败
            System.out.println(caseName + " :: Fail :: " + set.iterator().next().getMessage());
        } else {
            // 校验通过
            System.out.println(caseName + " :: Succeed");
        }
    }

}

运行示例,输出如下:

case1 :: Fail :: 名称必须为空
case2 :: Fail :: 名称必须为空
case3 :: Succeed


说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号