Creating Custom Annotations for Validation in Spring Boot
Nguyen Hai Dang (Eric)
? Software Engineer | Backend | Devops | Database Optimization | AWS Cloud | Azure Cloud | Java | Let's connect?
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.
2. Setup
We need to add the spring-boot-starter-validation dependency to our pom.xml file.
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.
Let's break down these annotations' components:
3.2. Creating the Validator
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.
领英推荐
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.
4.2. Creating the Validator
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.
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 !
?????Technical Consultant | RPA Developer in Power Platform
8 个月I'll keep this in mind
? Remote Fullstack & Backend Developer | Web Development, Database Optimization| PHP, Node.js, MySQL, MongoDB
8 个月Very helpful!
??Project Team Leader @ CNV Loyalty | Database Administrator | Problem Solving | Software Engineer
8 个月Thanks bro
?Database Administrator at Wecommit Vi?t Nam
8 个月Good to know!