2

鉴于有无法解决的占位符某些应用程序配置,如下所示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绑定的行为?

+1

你应该,但'@ Validated'上个类和'@ NotNull'或'@ NotEmpty'在球场上和验证工作,你必须有一个您的类路径上的JSR-303验证程序,例如“hibernate-validation”。只添加注释'@ Validation'不会产生任何结果。 –

回答

1

我在10分钟前就有同样的问题! 试着在你的配置中添加这个bean:

@Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); 
     propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true); 
     return propertySourcesPlaceholderConfigurer; 
    } 
+0

好找,但实际上这是解决相反问题的方法。我不想隐瞒错误,我想保留它。 –

+0

你必须手动使你的属性类实现'InitializingBean'并重写'afterPropertiesSet()'方法,你可以通过反射每个字段的值来检查并抛出异常,以防它们为null。 – DeejonZ

+0

这听起来不太优雅,除了属性不会最终为空,它们最终还是嵌入在字符串中的占位符值。 –