首页 > 解决方案 > 如何在 Spring Boot 中从命令行解析链接?

问题描述

XML 文件的链接作为命令行参数传递给应用程序。链接的格式如下:type:path,其中type是链接的类型,path是文件的路径。该链接定义了以 XML 格式加载数据的来源。链接类型(type):file(外部文件)、classpath(classpath中的文件)、url(URL)。示例:文件:input.xml,类路径:input.xml,url:文件:/input.xml。我怎样才能收到文件?我试过@Value,但它只能传递常量。

标签: javaspring-bootspring-annotations

解决方案


实现 ApplicationRunner以通过ApplicationArguments 获取第一个位置参数 。有多种方法可以定位资源,示例使用 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.
         */
    }
}

推荐阅读