Adiltst
Adiltst

Reputation: 23

Spring Boot Validation with environment variable

I would like to put the value of a spring boot environment variable into a validation annotation (@Min, @Max), but i don't know how to do it. Here is my code :

public class MessageDTO {

@Value("${validationMinMax.min}")
private Integer min;

@JsonProperty("Message_ID")
@NotBlank(message = "messageId cannot be blank.")
@Pattern(regexp = "\\w+", message = "messageId don't suits the pattern")
private String messageId;

@JsonProperty("Message_Type")
@NotBlank(message = "messageType cannot be blank")
private String messageType;

@JsonProperty("EO_ID")
@NotBlank(message = "eoId cannot be blank")
private String eoId;

@JsonProperty("UI_Type")
@NotNull(message = "uiType cannot be null")
@Min(1)
@Max(3)
private Integer uiType;

And here is my application.yml :

server:
  port: 8080 
spring:
  data:
    cassandra:
      keyspace-name: message_keyspace
      port: 9042
      contact-points:
        - localhost

validationMinMax:
  min: 1
  max: 3

I would like to put the field "min" and "max" of my yml into the annotation field @Min() and @Max() of my attribute uiType. Does anyone knows how to do it ? Thanks in advance for your help !

Upvotes: 2

Views: 1945

Answers (1)

Benjamin M
Benjamin M

Reputation: 24567

You can write your own validation annotation with a custom validator. In this validator you can autowire spring beans and inject configuration properties:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { MyValidator.class })
@Documented
public @interface MyValidationAnnotation {
    String message() default "";

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

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

The validator class:

public class MyValidator implements ConstraintValidator<MyValidationAnnotation, Integer> {

    @Autowired
    private MyService service;

    public void initialize(MyValidationAnnotation constraintAnnotation) {
      // ...
    }

    public boolean isValid(Integer value, ConstraintValidatorContext context) {
      if(service.validate(value)) {
        return true;
      } else {
        return false;
      }
    }

}

And then use it:

@MyValidationAnnotation
Integer foo;

Upvotes: 1

Related Questions