【问题标题】:How to parse link from command line in Spring boot?如何在 Spring Boot 中从命令行解析链接?
【发布时间】:2021-12-02 12:02:30
【问题描述】:
XML 文件的链接作为命令行参数传递给应用程序。链接的格式如下:type:path,其中type是链接的类型,path是文件的路径。该链接定义了以 XML 格式加载数据的来源。链接类型(type):file(外部文件)、classpath(classpath中的文件)、url(URL)。示例:文件:input.xml,类路径:input.xml,url:文件:/input.xml。
我怎样才能收到文件?我试过@Value,但它只能传递常量。
【问题讨论】:
标签:
java
spring-boot
spring-annotations
【解决方案1】:
实施
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.
*/
}
}