2017-02-23 54 views
1

我有以下彈簧組件。我想找到一個更優雅的注入配置值的方法。@Value強制啓動驗證

@Component 
public class Clazz { 

    @Value("${config.value.foo:#{null}}") 
    public String foo; 

    @PostConstruct 
    public validateFoo() throws ConfigException { 
     if (foo == null || "".equals(foo)) { 
      throw new ConfigException("Please provide config"); 
     } 
    } 
} 

我使用yaml configs。如果我不添加#{null},配置名稱(config.value.foo)將被注入String。另外,如果配置爲空或空,我希望Spring Boot應用程序不啓動。

是否有另一個註釋將注入配置值,並拋出異常,如果該值沒有配置或爲空?

編輯:

正如評論指出@Value默認行爲是拋出失蹤配置例外。我測試了這個,並在一個新的項目上使用了相同的配置。如果我刪除配置值,我得到:java.lang.IllegalArgumentException: Could not resolve placeholder我想我沒有得到一個異常,因爲我導入了一些庫。

+0

這已經是默認行爲,如果@ Value無法解析,它會炸燬。如果不是這種情況,在您的設置中配置錯誤。 –

+0

@ M.Deinum它不會拋出任何異常。我正在使用spring啓動和yaml配置。它只是注入配置名稱 – user1121883

+0

然後,你在配置中做了一些奇怪的事情,違反了默認行爲。 –

回答

0

如果有喜歡的一些代碼,這可能會發生:

PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); 
c.setIgnoreUnresolvablePlaceholders(true); 

我已經在我的項目沒有這樣的代碼,所以我增加了一個斷點setIgnoreUnresolvablePlaceholders這種方法被稱爲:

"[email protected]" prio=5 tid=0x1 nid=NA runnable 
    java.lang.Thread.State: RUNNABLE 
     at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.setIgnoreUnresolvablePlaceholders(PlaceholderConfigurerSupport.java:178) 
     at springfox.documentation.swagger.configuration.SwaggerCommonConfiguration.swaggerProperties(SwaggerCommonConfiguration.java:38) 
     at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-1) 
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 

所以問題是由springfox觸發的。我也從我的項目中禁用了swagger(刪除@EnableSwagger2),然後@Value按預期工作,並在丟失配置時拋出異常