Spring Boot CommandLineRunner: filter option argument

Given the Spring Boot CommandLineRunner , I would like to know how to filter out the "switch" options passed to Spring Boot as an external configuration.

For example, using

 @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); } } } 

I can call java -jar myJar.jar /tmp/file1 /tmp/file2 and the service will be called for both files.

But if I add a Spring parameter, for example java -jar myJar.jar /tmp/file1 /tmp/file2 --spring.config.name=myproject , then the configuration name will be updated (correctly!), But the service is also called for the file ./--spring.config.name=myproject , which of course does not exist.

I know that I can manually filter by file name with something like

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

But since all these components came from Spring, I wonder if there is an option somewhere that allows it to be controlled, and to ensure that the strings parameter passed to the run method does not contain any property parameters already analyzed at the application level.

+6
source share
4 answers

Thanks to the @AndyWilkinson improvement report, the ApplicationRunner interface was added in Spring Boot 1.3.0 (still in the Milestones for Now section, but will be released soon, I hope)

Here you can use and solve the problem:

 @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); } } } 
+6
source

In this case, there is no support for Spring Boot. I discovered the improvement problem so that we could consider it for a future version.

+2
source

One option is to use the Commons CLI in the run () of your CommandLineRunner impl.

There is a related question that may interest you.

+1
source

Here is another solution:

 @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; } } 

Then run the program:

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

Source: https://habr.com/ru/post/978511/


All Articles