首页 > 解决方案 > 如何将 YML 值放入 @Pattern(regexp = "HELLO|WORLD")

问题描述

我想将“HELLO|WORLD”值移动到 YML 文件中。然后在正则表达式中调用 YML 文件中的值。

例如,以下是 YAML 文件 YML FILE

valid-caller-value: HELLO|WORLD

获取 YAML 值的 Java 类

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

使用正则表达式验证的 Java 类

 @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;
    }

我想做与此类似的事情,而不是字符串。

@Pattern(regexp = properties.getValidCallerValue())

我已经尝试过以下注释。他们都没有工作

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

有可能实现这一目标吗?

注意:我真的不想使用常量。

标签: javaregexspringhibernateyaml

解决方案


我不知道在@Pattern注释中使用 SpEL 的任何方法。有一种方法可以像这样外部化正则表达式,但它涉及创建您自己的验证注释。我不知道这是否适合您,但这样的事情应该可行。

注解

@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 { };
}

验证器

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();
    }
}

推荐阅读