java - 如何在 Spring Boot 中从命令行解析链接?
问题描述
XML 文件的链接作为命令行参数传递给应用程序。链接的格式如下:type:path,其中type是链接的类型,path是文件的路径。该链接定义了以 XML 格式加载数据的来源。链接类型(type):file(外部文件)、classpath(classpath中的文件)、url(URL)。示例:文件:input.xml,类路径:input.xml,url:文件:/input.xml。我怎样才能收到文件?我试过@Value,但它只能传递常量。
解决方案
实现 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.
*/
}
}
推荐阅读
- django - Django:过滤另一行的值
- swift - 如何在 Heroku 上使用 swift 安全地处理 Slack 的 API 令牌?
- node.js - 等待服务响应,然后继续进行?
- vue.js - Vuejs 中的 SlickGrid 和溢出:滚动
- mysql - 查询大量行时创建高效存储过程的问题
- asp.net - 一起返回两个实体框架查询结果
- javascript - 在 Express 中的 app.listen 之前等待异步函数完成
- java - 如何将麦克风权限授予 Java 应用程序(macOS Mojave 及更高版本)?
- automata - 图灵机接受单词“1”可排列成正方形
- spring - 如果我添加 @EnableJpaRepositories 注释,服务类 Autowire 返回 Null