Introduction
Validating user input is a critical part of any application to ensure data integrity and security. Spring Boot provides a robust mechanism for validation using annotations from the Javax.validation package. While standard annotations like @NotNull, @Size, and @Email cover many common validation scenarios, there are times when you need custom validation logic. In such cases, creating custom annotations and validators can be very effective.
This article will guide you through creating custom annotations and validators in a Spring Boot application with a practical example.
Creating Custom Annotations
Step 1. Create a Custom Annotation.
First, let's create a custom annotation @ValidAge to validate that a person's age falls within a specified range.
ValidAge.java
package com.example.demo.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = AgeValidator.class)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidAge {
String message() default "Invalid age: Age must be between 18 and 60";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int min() default 18;
int max() default 60;
}
Step 2. Create the Validator Class.
Next, we need to implement the ConstraintValidator interface to define the validation logic.
AgeValidator.java
package com.example.demo.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class AgeValidator implements ConstraintValidator<ValidAge, Integer> {
private int min;
private int max;
@Override
public void initialize(ValidAge validAge) {
this.min = validAge.min();
this.max = validAge.max();
}
@Override
public boolean isValid(Integer age, ConstraintValidatorContext context) {
if (age == null) {
return false;
}
return age >= min && age <= max;
}
}
Using Custom Annotations in a Spring Boot Application
Step 3. Create an Entity Class.
We'll create a User entity class that uses our custom @ValidAge annotation to validate the age field.
User.java
package com.example.demo.entity;
import com.example.demo.validation.ValidAge;
public class User {
private Long id;
private String name;
@ValidAge
private Integer age;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Onkar SharmaPosted Jul 6, 2024, 3:45 PM
Thanks for sharing useful and informative information, Aman Gupta!
Amit KumarPosted Jul 4, 2024, 10:22 AM
Great guide on creating custom annotations and validators in Spring Boot. Very practical and clear!