Close

Spring Framework - Creating Custom Validation Annotation Examples

Spring Framework 

Creating new annotation for validation

package com.logicbig.example;

import javax.validation.Constraint;
import javax.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 javax.validation.ConstraintValidator;
import javax.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 javax.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 javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.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>> violations = validator.validate(book);
for (ConstraintViolation<Book> violation : violations) {
String message = violation.getMessage();
Path path = violation.getPropertyPath();
System.err.println(path+" "+message);
}
}
}

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 javax.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

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




See Also