2014-11-21 99 views
6

考虑到Spring Boot CommandLineRunner应用程序,我想知道如何筛选传递给Spring Boot的“开关”选项作为外部配置。Spring Boot CommandLineRunner:筛选器选项参数

例如,使用:

@Component 
public class FileProcessingCommandLine implements CommandLineRunner { 
    @Override 
    public void run(String... strings) throws Exception { 
     for (String filename: strings) { 
      File file = new File(filename); 
      service.doSomething(file); 
     } 
    } 
} 

我可以打电话java -jar myJar.jar /tmp/file1 /tmp/file2,该服务将被调用这两个文件。

但是,如果我添加一个弹簧参数,如java -jar myJar.jar /tmp/file1 /tmp/file2 --spring.config.name=myproject那么配置名称会更新(正确!),但该服务也被称为文件./--spring.config.name=myproject当然不存在。

我知道我可以手动过滤的文件名以类似

if (!filename.startsWith("--")) ... 

但作为这一切的组件从春天来了,我不知道是否有没有选择的地方,让它管理它,并确保传递给run方法的strings参数不包含应用程序级别已解析的所有属性选项。

回答

6

由于@AndyWilkinson增强报告,在春季启动在加入ApplicationRunner接口1.3.0(仍然是里程碑但是很快就会发布我希望)

这里使用它的方式来解决问题:

@Component 
public class FileProcessingCommandLine implements ApplicationRunner { 
    @Override 
    public void run(ApplicationArguments applicationArguments) throws Exception { 
     for (String filename : applicationArguments.getNonOptionArgs()) 
      File file = new File(filename); 
      service.doSomething(file); 
     } 
    } 
} 
2

目前在Spring Boot中没有这方面的支持。我已打开an enhancement issue,以便我们可以考虑将来发布。

+0

感谢您考虑了! – 2014-11-25 08:41:11

+0

有没有关于这方面的消息?过去6个月至少有一千人看过这个问题。 – 2015-06-17 11:26:51

+0

看起来像这样已经解决了我们现在有一个如何使用'ApplicationArguments'的例子吗? – Jackie 2016-08-08 14:05:26

1

一个选项是在CommandLineRunner impl的run()中使用Commons CLI

您可能有兴趣的相关question

+0

那么,当你看到替代品列表......这就是为什么我希望Spring选择它的方式,而不必调查所有可能的手段来做到这一点。 无论如何,谢谢! – 2014-12-22 11:08:35

+0

这是一个很好的选择 – aliopi 2016-02-10 09:11:52

1

这里是另一种解决方案:

@Component 
public class FileProcessingCommandLine implements CommandLineRunner { 

    @Autowired 
    private ApplicationConfig config; 

    @Override 
    public void run(String... strings) throws Exception { 

     for (String filename: config.getFiles()) { 
      File file = new File(filename); 
      service.doSomething(file); 
     } 
    } 
} 


@Configuration 
@EnableConfigurationProperties 
public class ApplicationConfig { 
    private String[] files; 

    public String[] getFiles() { 
     return files; 
    } 

    public void setFiles(String[] files) { 
     this.files = files; 
    } 
} 

然后运行该程序:

java -jar myJar.jar --files=/tmp/file1,/tmp/file2 --spring.config.name=myproject 
+0

谢谢! 但这仍然是一种解决方法,我认为我们在这里会失去使用Spring提供的CommandLineRunner接口的兴趣。 – 2014-12-29 23:21:37