Search code examples
javaspring-bootspring-annotations

How to parse link from command line in Spring boot?


A link to the XML file is passed to the application as a command line parameter. The link has the following format: type: path, where type is the type of the link, path is the path to the file. The link defines the source from which the data is loaded in XML format. Link type (type): file (external file), classpath (file in classpath), url (URL). Examples: file: input.xml, classpath: input.xml, url: file: /input.xml. How can I receive the file? I tried @Value, but it can pass only constants.


Solution

  • Implement ApplicationRunner to get the first positional argument through ApplicationArguments. There are multiple ways to locate a resource and the example uses DefaultResourceLoader.

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.core.io.DefaultResourceLoader;
    import org.springframework.core.io.Resource;
    
    @SpringBootApplication
    @NoArgsConstructor @ToString @Log4j2
    public class Command implements ApplicationRunner {
        public static void main(String[] argv) throws Exception {
            new SpringApplicationBuilder(Command.class).run(argv);
        }
    
        @Override
        public void run(ApplicationArguments arguments) throws Exception {
            /*
             * Get the first optional argument.
             */
            String link = arguments.getNonOptionArgs().get(0);
            /*
             * Get the resource.
             */
            Resource resource = new DefaultResourceLoader().getResource(link);
            /*
             * Command implementation; command completes when this method
             * completes.
             */
        }
    }