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

Tags: , , , ,

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

    public class Properties {
        private String validCallerValue;

Java class that use regex validation

    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.


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.


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

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


public class PropertyPatternValidator implements ConstraintValidator<PropertyPattern, String> {

    private Pattern pattern;

    public void initialize(PropertyPattern propertyPattern) {

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

    public boolean isValid(String value, ConstraintValidatorContext context) {

        Matcher matcher = pattern.matcher(value);
        return matcher.matches();

Source: stackoverflow