在 spring boot 中创建用于验证的自定义注释
- 概述
虽然 spring 标准注释(@notblank、@notnull、@min、@size 等)涵盖了验证用户输入时的许多用例,但有时我们需要为更具体的输入类型创建自定义验证逻辑。在本文中,我将演示如何创建自定义注释以进行验证。
- 设置
我们需要将 spring-boot-starter-validation 依赖项添加到我们的 pom.xml 文件中。
- 文件mime类型验证器
@requiredargsconstructor public class filemimetypevalidator implements constraintvalidator{ private final tika tika; private list 登录后复制 这些类是 constraintvalidator 接口的实现,包含实际的验证逻辑。 对于 filemimetypevalidator,我们将使用 apache tika(一个旨在从多种类型的文档中提取元数据和内容的工具包)。 3.3 应用注释 让我们创建一个 testuploadrequest 类,用于处理文件上传,特别是 pdf 文件。 @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 responseentitymimetypes; @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); } } 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 extends payload>[] 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 ResponseEntityregister(@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 Boot 中创建用于验证的自定义注释的详细内容,更多请关注php中文网其它相关文章!


MP4 天前
发表在:MagicEXIF通用注册机 v1.13明亮的 旅行分享! 做得真好。
BrendanWaida8 天前
发表在:11日20日,星期四,在这里每天60秒读懂世界!При выборе автономно...
JosephJaf10 天前
发表在:MagicEXIF通用注册机 v1.13我尊重这样的项目, 这里展示真正的旅游。...
Frankcic11 天前
发表在:11日20日,星期四,在这里每天60秒读懂世界!Для блога может быть...
Stevedaf20 天前
发表在:MagicEXIF通用注册机 v1.13所有文章都令人印象深刻。继续保持 真诚。...
Stevedaf20 天前
发表在:Intel XTU中文补丁 1.13我经常访问 关于旅行的资源。有趣阅读游记...
Stevedaf20 天前
发表在:MagicEXIF通用注册机 v1.13我常常想, 能像你们一样多旅行。感谢激励...
Stevedaf20 天前
发表在:Intel XTU中文补丁 1.13很高兴阅读 有用的内容。十分 很有意思。...
Stevedaf21 天前
发表在:MagicEXIF通用注册机 v1.13我早就想, 能像你们一样多旅行。谢谢启发...
Stevedaf21 天前
发表在:Intel XTU中文补丁 1.13我一直梦想, 那么放松地度假。感谢激励。...