Spring Boot CommandLineRunner:filter选项参数
考虑到Spring Boot CommandLineRunner
应用程序,我想知道如何过滤传递给Spring Boot的“switch”选项作为外部化配置。
例如,用:
@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
并且将为这两个文件调用该服务。
但是,如果我添加一个Spring参数,比如java -jar myJar.jar /tmp/file1 /tmp/file2 --spring.config.name=myproject
那么配置名称会更新(正确!),但该服务也会调用文件./--spring.config.name=myproject
当然不存在。
我知道我可以用类似的东西手动过滤文件名
if (!filename.startsWith("--")) ...
但由于所有这些组件都来自Spring,我想知道是否有一个选项可以让它管理它,并确保传递给run
方法的strings
参数不会包含已在应用程序级别解析的所有属性选项。
感谢@AndyWilkinson增强报告,在Spring Boot 1.3.0中添加了ApplicationRunner
接口(目前仍在里程碑中,但我希望很快就会发布)
在这里使用它并解决问题的方式:
@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); } } }
目前Spring Boot中不支持此function。 我已经打开了一个增强问题,以便我们可以考虑将来发布。
一种选择是在CommandLineRunner impl的run()中使用Commons CLI 。
您可能感兴趣的是一个相关问题 。
这是另一个解决方案:
@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