Skip to content
Advertisement

How to put YML value inside the @Pattern(regexp = “HELLO|WORLD”)

I want to move the “HELLO|WORLD” value to the YML file. Then call the value from YML file inside the regexp.

For example, Following is the YAML file YML FILE

valid-caller-value: HELLO|WORLD

Java class to get the YAML value

 @Configuration
    @ConfigurationProperties
    @Data
    @NoArgsConstructor
    public class Properties {
        
        private String validCallerValue;
    
    }

Java class that use regex validation

 @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SearchCriteriaValidator
    public class classOne {    
    @Pattern(regexp = ""HELLO|WORLD", flags = Pattern.Flag.CASE_INSENSITIVE, message = "callerValue key has invalid value. No leading or trailing space(s) are allowed")
        protected String callerValue;
    }

Instead of a string, I want to do something similar to this.

@Pattern(regexp = properties.getValidCallerValue())

I have already tried the following annotation. And none of them worked

@Pattern(regexp = "#\{@properties.getValidCallerValue()}")
@Pattern(regexp = "$\{properties.getValidCallerValue()}

Is it possible to achieve this?

NOTE: I don’t really want to use a constant.

Advertisement

Answer

I don’t know of any way to use SpEL in a @Pattern annotation. There is a way to externalize regexp’s like that, but it involves creating your own validation annotation. I don’t know if that is an option for you, but something like this should work.

Annotation

@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = PropertyPatternValidator.class)
@Documented
public @interface PropertyPattern {

    String message() default "value doesn't match pattern";
    String property();
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

Validator

public class PropertyPatternValidator implements ConstraintValidator<PropertyPattern, String> {

    private Pattern pattern;

    @Override
    public void initialize(PropertyPattern propertyPattern) {

        final String property = propertyPattern.property();
        final Environment environment = SpringContextHolder.getBean(Environment.class);
        pattern = Pattern.compile(environment.getProperty(property));
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement