2017-04-14 66 views
0

我正在寫一個Spring引導應用程序,我想驗證所有預期的參數或外部化屬性是在我的應用程序運行之前設置的。當我能做到這一點? 我找到commons-cli或args4j庫,但我沒有如何使用它與Spring啓動應用程序,如果它是一個很好的解決方案。謝謝Spring引導和參數驗證

+0

你的意思是設置爲不是'null'嗎? – ndrone

回答

0

把你的驗證邏輯放在Spring引導主要方法中。在Spring引導應用程序中沒有獨立的方式來使用這些庫。你可以在你的主要方法中添加你的驗證代碼,解析參數並進行驗證。 U可以使用任何參數解析器庫。

@SpringBootApplication 
public class MyApplication{ 
    public static void main(String[] args){ 
     validateArguments(args); 
     SpringApplication.run(MyApplication.class); 
    } 
    private static validateArguments(args){ 
     // validation logic - If validation fails throw IllegalStateException(); 
    } 
} 
+0

謝謝我將使用您的解決方案 – atoua

0

有幾個這樣做。此鏈接解釋了所有可用https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

如果你只是檢查NOT NULL然後您就可以使用@Value像這樣

@Configuration 
public class ApplicationConfiguration 
{ 
    @Value("${name}") 
    private String name; 
} 

與有關應用程序,如果該值將停止在啓動null

如果您有其他需要確定其特性的特性,您可以使用@ConfigurationProperties

@ConfigurationProperties(prefix = "test") 
public class ConfigProps 
{ 
    private String name; 

    public String getName() 
    { 
      return name; 
    } 
} 

@Configuration 
@EnableConfigurationProperties 
public class AppConfig 
{ 
    @Autowired 
    public AppConfig(ConfigProps configProps) 
    { 
      if (!"test".equals(configProps.getName()) 
      { 
       throw new IllegalArugmentException("name not correct value"); 
      } 
    } 
}