0

0

在 Spring Boot 中创建用于验证的自定义注释

WBOY

WBOY

发布时间:2024-07-25 08:10:37

|

363人浏览过

|

来源于dev.to

转载

在 spring boot 中创建用于验证的自定义注释

在 spring boot 中创建用于验证的自定义注释

1. 概述

虽然 spring 标准注释(@notblank、@notnull、@min、@size 等)涵盖了验证用户输入时的许多用例,但有时我们需要为更具体的输入类型创建自定义验证逻辑。在本文中,我将演示如何创建自定义注释以进行验证。

2. 设置

我们需要将 spring-boot-starter-validation 依赖项添加到我们的 pom.xml 文件中。


    org.springframework.boot
    spring-boot-starter-validation

3. 自定义字段级别验证

3.1 创建注释

让我们创建自定义注释来验证文件属性,例如文件扩展名、文件大小和 mime 类型。

  • 有效文件扩展名
@target({elementtype.field})
@retention(retentionpolicy.runtime)
@documented
@constraint(
        validatedby = {fileextensionvalidator.class}
)
public @interface validfileextension {
    string[] extensions() default {};

    string message() default "{constraints.validfileextension.message}";

    class[] groups() default {};

    class[] payload() default {};
}
  • 有效文件最大大小
@target({elementtype.field})
@retention(retentionpolicy.runtime)
@documented
@constraint(
        validatedby = {filemaxsizevalidator.class}
)
public @interface validfilemaxsize {
    long maxsize() default long.max_value; // mb

    string message() default "{constraints.validfilemaxsize.message}";

    class[] groups() default {};

    class[] payload() default {};
}

  • 文件mime类型验证器
@target({elementtype.field})
@retention(retentionpolicy.runtime)
@documented
@constraint(
        validatedby = {filemimetypevalidator.class}
)
public @interface validfilemimetype {
    string[] mimetypes() default {};

    string message() default "{constraints.validfilemimetype.message}";

    class[] groups() default {};

    class[] payload() default {};
}

让我们分解一下这些注释的组成部分:

  • @constraint:指定负责验证逻辑的验证器类。
  • @target({elementtype.field}):表示该注解只能应用于字段。
  • message(): 验证失败时默认的错误消息。

3.2 创建验证器

  • 文件扩展名验证器
public class fileextensionvalidator implements constraintvalidator {

    private list extensions;

    @override
    public void initialize(validfileextension constraintannotation) {
        extensions = list.of(constraintannotation.extensions());
    }

    @override
    public boolean isvalid(multipartfile file, constraintvalidatorcontext constraintvalidatorcontext) {
        if (file == null || file.isempty()) {
            return true;
        }
        var extension = filenameutils.getextension(file.getoriginalfilename());
        return stringutils.isnotblank(extension) && extensions.contains(extension.tolowercase());
    }
}
  • 文件最大大小验证器
public class filemaxsizevalidator implements constraintvalidator {

    private long maxsizeinbytes;

    @override
    public void initialize(validfilemaxsize constraintannotation) {
        maxsizeinbytes = constraintannotation.maxsize() * 1024 * 1024;
    }

    @override
    public boolean isvalid(multipartfile file, constraintvalidatorcontext constraintvalidatorcontext) {
        return file == null || file.isempty() || file.getsize() <= maxsizeinbytes;
    }
}

  • 文件mime类型验证器
@requiredargsconstructor
public class filemimetypevalidator implements constraintvalidator {

    private final tika tika;
    private list mimetypes;

    @override
    public void initialize(validfilemimetype constraintannotation) {
        mimetypes = list.of(constraintannotation.mimetypes());
    }

    @sneakythrows
    @override
    public boolean isvalid(multipartfile file, constraintvalidatorcontext constraintvalidatorcontext) {
        if (file == null || file.isempty()) {
            return true;
        }
        var detect = tika.detect(tikainputstream.get(file.getinputstream()));
        return mimetypes.contains(detect);
    }
}

这些类是 constraintvalidator 接口的实现,包含实际的验证逻辑。
对于 filemimetypevalidator,我们将使用 apache tika(一个旨在从多种类型的文档中提取元数据和内容的工具包)。

3.3 应用注释

让我们创建一个 testuploadrequest 类,用于处理文件上传,特别是 pdf 文件。

AI帮个忙
AI帮个忙

多功能AI小工具,帮你快速生成周报、日报、邮、简历等

下载
@data
public class testuploadrequest {

    @notnull
    @validfilemaxsize(maxsize = 10)
    @validfileextension(extensions = {"pdf"})
    @validfilemimetype(mimetypes = {"application/pdf"})
    private multipartfile pdffile;

}

@restcontroller
@validated
@requestmapping("/test")
public class testcontroller {

    @postmapping(value = "/upload", consumes = {mediatype.multipart_form_data_value})
    public responseentity testupload(@valid @modelattribute testuploadrequest request) {
        return responseentity.ok("test upload");
    }
}

  • @target({elementtype.type}):表示该注解的目标是类型声明。

4. 自定义类级别验证

还可以在类级别定义自定义验证注释来验证类内的字段组合。

4.1 创建注释

让我们创建 @passwordmatches 注解来确保类中的两个密码字段匹配。

@target({elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@constraint(
        validatedby = {passwordmatchesvalidator.class}
)
public @interface passwordmatches {
    string message() default "{constraints.passwordmatches.message}";

    class[] groups() default {};

    class[] payload() default {};
}

4.2 创建验证器

  • 密码dto
public interface passworddto {
    string getpassword();

    string getconfirmpassword();
}


  • 密码匹配验证器
public class passwordmatchesvalidator implements constraintvalidator {

    @override
    public boolean isvalid(passworddto password, constraintvalidatorcontext constraintvalidatorcontext) {
        return stringutils.equals(password.getpassword(), password.getconfirmpassword());
    }
}

passworddto 接口是包含密码和确认密码字段的对象的接口。
passwordmatchesvalidator 类实现 constraintvalidator 接口,并包含验证密码和确认密码字段是否匹配的逻辑。

4.3 应用注释

让我们创建一个 registeraccountrequest 类,用于处理用户注册数据。

@passwordmatches
@data
public class registeraccountrequest implements passworddto {

    @notblank
    private string username;

    @notblank
    @email
    private string email;

    @notblank
    @tostring.exclude
    private string password;

    @notblank
    @tostring.exclude
    private string confirmpassword;
}

@RestController
@Validated
@RequestMapping("/auth")
public class AuthController {

    @PostMapping("/register")
    public ResponseEntity register(@RequestBody @Valid RegisterAccountRequest request) {
        return ResponseEntity.ok("register success");
    }
}

5. 总结

在这篇短文中,我们发现创建自定义注释来验证字段或类是多么容易。本文中的代码可以在我的 github 上找到。

  • spring-boot-微服务
  • 用户服务

6. 参考文献

  • 拜尔东。 (日期不详)。 spring mvc 自定义验证器。已检索 来自 https://www.baeldung.com/spring-mvc-custom-validator

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

98

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

384

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

64

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

13

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

104

2025.12.24

pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1852

2024.04.01

xml怎么变成word
xml怎么变成word

步骤:1. 导入 xml 文件;2. 选择 xml 结构;3. 映射 xml 元素到 word 元素;4. 生成 word 文档。提示:确保 xml 文件结构良好,并预览 word 文档以验证转换是否成功。想了解更多xml的相关内容,可以阅读本专题下面的文章。

2080

2024.08.01

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

150

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.4万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.5万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号