spring - Spring Boot 配置属性 Unresolved 占位符验证

标签 spring validation spring-boot configuration spring-boot-configuration

给定一些带有无法解析占位符的应用程序配置,如以下 application.yml

my:
  thing: ${missing-placeholder}/whatever

当我使用@Value注释时,配置文件中的占位符会被验证,所以在这种情况下:

package com.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PropValues {
    @Value("${my.thing}") String thing;
    public String getThing() { return thing; }
}

我得到一个IllegalArgumentException:无法解析值“${missing-placeholder}/whatever”中的占位符“missing-placeholder”。这是因为该值是由 AbstractBeanFactory.resolveEmbeddedValue 直接设置的,并且没有任何东西可以捕获 PropertyPlaceholderHelper.parseStringValue

抛出的异常。

但是,希望转向 @ConfigurationProperties 样式,我注意到缺少此验证,例如在本例中:

package com.test;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "my")
public class Props {
    private String thing;
    public String getThing() { return thing; }    
    public void setThing(String thing) { this.thing = thing; }
}

没有异常(exception)。我可以看到 PropertySourcesPropertyValues.getEnumerableProperty 捕获了带有注释 //可能无法解析占位符,在此处忽略它 的异常,并将无效值收集到其内部映射中。后续数据绑定(bind)不会检查未解析的占位符。

我检查过,简单地将 @Validated@Valid 注释应用于类和字段并没有帮助。

是否有任何方法可以通过 ConfigurationProperties 绑定(bind)保留在未解析的占位符上引发异常的行为?

最佳答案

显然没有更好的解决方案。至少这比 afterPropertiesSet() 好一些。

@Data
@Validated // enables javax.validation JSR-303
@ConfigurationProperties("my.config")
public static class ConfigProperties {
    // with @ConfigurationProperties (differently than @Value) there is no exception if a placeholder is NOT RESOLVED. So manual validation is required!
    @Pattern(regexp = ".*\$\{.*", message = "unresolved placeholder")
    private String uri;
    // ...
}

更新:我第一次得到了正则表达式错误。它匹配整个输入(不仅仅是 java.util.regex.Matcher#find())。

关于spring - Spring Boot 配置属性 Unresolved 占位符验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43493346/

相关文章:

java - Thymeleaf 迭代状态变量为 null

java - 以编程方式实例化具有 Spring 生命周期注释的类的对象

java - 在方法级别而不是类级别的基本 Jax-RS PATH 配置

spring - 当 session 未锁定时无法从父级中删除

validation - Jersey 自定义验证器单元测试

spring-boot - Spring Boot Swagger 使用 Spring Fox 实现失败启动 bean 'documentationPluginsBootstrapper'

java - Spring Tool Suite(Eclipse)项目运行问题

javascript - 手动设置自定义验证消息时如何触发 HTML5 验证错误弹出窗口?

javascript - 只允许 6 位数字或 8 位数字(保留 2 位小数)

spring-boot - 如何在 spring-boot 应用程序中为 swagger-ui 指定我的 restful API