2017-04-14 61 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"); 
      } 
    } 
}