【发布时间】:2017-09-15 13:01:12
【问题描述】:
给定一些具有不可解析占位符的应用程序配置,如以下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: Could not resolve placeholder 'missing-placeholder' in value "${missing-placeholder}/whatever"。这是因为该值是由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; }
}
也不例外。我可以看到PropertySourcesPropertyValues.getEnumerableProperty 使用注释// Probably could not resolve placeholders, ignore it here 捕获异常并将无效值收集到其内部映射中。后续数据绑定不会检查未解析的占位符。
我检查了简单地将 @Validated 和 @Valid 注释应用于类和字段没有帮助。
是否有任何方法可以保留在具有ConfigurationProperties 绑定的未解析占位符上引发异常的行为?
【问题讨论】:
-
您应该在课堂上使用
@Validated,在现场使用@NotNull或@NotEmpty,并且要进行验证,您必须在类路径上使用JSR-303 验证器,例如@987654338 @。仅添加注释@Validation不会产生任何结果。 -
有人找到解决方案了吗?
标签: spring validation spring-boot configuration spring-boot-configuration