java - 如何将 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()}
有可能实现这一目标吗?
注意:我真的不想使用常量。
解决方案
我不知道在@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();
}
}
推荐阅读
- php - 如何在没有键的情况下使用 PHP 获取内部数组值
- api - 调用涂鸦智能API,调用接口报错码:1106,权限被拒绝,如何解决?
- python-sphinx - 如何链接 reStructuredText 中的重复目标?
- python - Locust-重复用户列表
- python - amazon iam 在 boto3 中获得内联政策声明
- sql - 如何计算所有行的中位数?
- django - 使用本地包在 Microsoft Azure 上部署 Django 应用
- c++ - github操作中的cpplinter
- javascript - 如何在 Javascript 中不显示 URL 的情况下创建链接?
- javascript - 我的 NativeBase 结果的标题组件是空的并且不在顶部