Joe*_*lor 6 validation configuration spring spring-boot spring-boot-configuration
给定一些具有无法解析的占位符的应用程序配置,如下所示 application.yml
my:
thing: ${missing-placeholder}/whatever
Run Code Online (Sandbox Code Playgroud)
使用@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; }
}
Run Code Online (Sandbox Code Playgroud)
我得到一个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; }
}
Run Code Online (Sandbox Code Playgroud)
也不例外。我可以看到PropertySourcesPropertyValues.getEnumerableProperty使用注释捕获了异常,// Probably could not resolve placeholders, ignore it here并将无效值收集到其内部映射中。后续数据绑定不会检查未解析的占位符。
我检查过,仅将@Validatedand @Valid注释应用于类和字段没有帮助。
有什么方法可以保留在具有ConfigurationProperties绑定的未解析占位符上引发异常的行为吗?
Dee*_*onZ -1
10 分钟前我也遇到了同样的问题!尝试在您的配置中添加此 bean:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2076 次 |
| 最近记录: |