Close

Spring Framework - Creating Custom Validation Annotation Examples

Spring Framework 

Creating new annotation for validation

package com.logicbig.example;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = LanguageValidator.class)
public @interface Language {

String message() default "must be a valid language display name," +
" found: ${validatedValue}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

Creating validator

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class LanguageValidator implements ConstraintValidator<Language, String> {
@Autowired
private LanguageProvider languageProvider;

@Override
public void initialize(Language constraintAnnotation) {
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return false;
}
return languageProvider.getLanguages()
.stream()
.anyMatch(value::equalsIgnoreCase);
}
}
package com.logicbig.example;

import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public interface LanguageProvider {

List<String> getLanguages();

@Component
public static class DefaultLanguageProvider implements LanguageProvider {

@Override
public List<String> getLanguages() {
List<String> languageList = new ArrayList<>();
for (Locale locale : Locale.getAvailableLocales()) {
languageList.add(locale.getDisplayLanguage());
}
return languageList;
}
}
}

Using new annotation on our POJO

package com.logicbig.example;

import jakarta.validation.constraints.NotNull;

public class Book {
@NotNull
private String name;
@Language
private String language;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getLanguage() {
return language;
}

public void setLanguage(String language) {
this.language = language;
}
}

Performing validation

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.util.Set;

@Component
public class ClientBean {
@Autowired
private Validator validator;

public void run() {
Book book = new Book();
book.setName("Alien Explorer");
book.setLanguage("Englis");

Set<ConstraintViolation<Book>> c = validator.validate(book);
if (c.size() > 0) {
System.err.println("validation errors:");
c.stream().map(v -> v.getMessage()).forEach(System.err::println);
}
}
}

Main class

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import jakarta.validation.Validator;

@Configuration
@ComponentScan
public class AppConfig {
@Bean
public Validator validatorFactory() {
return new LocalValidatorFactoryBean();
}

public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
AppConfig.class);

ClientBean bean = context.getBean(ClientBean.class);
bean.run();
}
}

Output

validation errors:
must be a valid language display name, found: Englis
Original Post




See Also