Creating Custom Annotations for Validation in Spring Boot

Creating Custom Annotations for Validation in Spring Boot

1. Overview

While Spring standard annotations (@NotBlank, @NotNull, @Min, @Size, etc.) cover many use cases when validating user input, there are times when we need to create custom validation logic for a more specific type of input. In this article, I will demonstrate how to create custom annotations for validation.

Creating Custom Annotations for Validation in Spring Boot

2. Setup

We need to add the spring-boot-starter-validation dependency to our pom.xml file.

pom.xml

3. Custom Field Level Validation

3.1 Creating the Annotation

Let’s create custom annotations?to to validate file attributes, such as file extension, file size, and MIME type.

ValidFileExtension
ValidFileMaxSize
FileMimeTypeValidator

Let's break down these annotations' components:

  • @Constraint: Specifies the validator class responsible for the validation logic.
  • @Target({ElementType.FIELD}): Indicates that this annotation can only be applied to fields.
  • message(): The default error message if the validation fails.

3.2. Creating the Validator

FileExtensionValidator
FileMaxSizeValidator
FileMimeTypeValidator

These classes are implementations of the ConstraintValidator interface and contain the actual validation logic.

For FileMimeTypeValidator, we will use Apache Tika (a toolkit designed to extract metadata and content from numerous types of documents).

3.3 Applying the Annotation

Let's create a TestUploadRequest class intended for handling file uploads, specifically for a PDF file.

TestUploadRequest
TestController

4. Custom Class Level Validation

A custom validation annotation can also be defined at the class level to validate a combination of fields within a class.

4.1 Creating the Annotation

Let’s create @PasswordMatches annotation?to ensure that two password fields match in a class.

PasswordMatches

  • @Target({ElementType.TYPE}): Indicates that this annotation targets a type declaration.

4.2. Creating the Validator

PasswordDto
PasswordMatchesValidator

The PasswordDto interface is an interface for objects that contain a password and a confirm password field.

The PasswordMatchesValidator class implements the ConstraintValidator interface and contains the logic for validating that the password and confirm password fields match.

4.3 Applying the Annotation

Let's create a RegisterAccountRequest class intended for handling user registration data.

RegisterAccountRequest
AuthController

5. Summary

In this short article, we discoverd how easy it is to to create custom annotations to verify a field or class. The code from this article is available over on my Github.

6. References

Thanks for sharing !

回复
Ng? H?ng Quang

?????Technical Consultant | RPA Developer in Power Platform

8 个月

I'll keep this in mind

Ngo Nguyen Cong

? Remote Fullstack & Backend Developer | Web Development, Database Optimization| PHP, Node.js, MySQL, MongoDB

8 个月

Very helpful!

回复
Báu Tr?n

??Project Team Leader @ CNV Loyalty | Database Administrator | Problem Solving | Software Engineer

8 个月

Thanks bro

回复
Manh Vu Dinh

?Database Administrator at Wecommit Vi?t Nam

8 个月

Good to know!

要查看或添加评论,请登录

Nguyen Hai Dang (Eric)的更多文章

  • 10 Useful Prompts to Enhance Your Learning ??

    10 Useful Prompts to Enhance Your Learning ??

    In today's fast-paced digital world, learning effectively is more important than ever. Whether you're diving into a new…

    8 条评论
  • Getting Started with Spring WebFlux

    Getting Started with Spring WebFlux

    Spring WebFlux is a reactive programming framework introduced in Spring 5. It provides a non-blocking, asynchronous…

    8 条评论
  • Understanding Database Isolation Levels: An Essential Overview

    Understanding Database Isolation Levels: An Essential Overview

    Database isolation levels define how transactions interact with each other in a database, particularly when multiple…

  • Apply Design Patterns In Java (Part 3)

    Apply Design Patterns In Java (Part 3)

    1. Overview Continuing from my previous article, we delve into three key design patterns: Facade, Mediator, and…

    2 条评论
  • Enhancing Oracle Database Performance with Interval Partitioning

    Enhancing Oracle Database Performance with Interval Partitioning

    Partitioning in Oracle Database is crucial for managing large datasets efficiently. Interval partitioning, a dynamic…

    9 条评论
  • Performance Pitfalls: Using Hints in Oracle Database

    Performance Pitfalls: Using Hints in Oracle Database

    Performance Pitfalls: Using Hints in Oracle Database In Oracle Database, hints can guide the optimizer to improve query…

    4 条评论
  • Apply Design Patterns In Java (Part 2)

    Apply Design Patterns In Java (Part 2)

    1. Overview Previously, we explored the Strategy and Factory Method design patterns (Link), which enhance flexibility…

    4 条评论
  • Apply Design Patterns In Java (Part 1)

    Apply Design Patterns In Java (Part 1)

    1. Overview Design patterns are proven valuable solutions that serve as a model for solving design problem and may be…

    4 条评论

社区洞察

其他会员也浏览了