gpt4 book ai didi

spring - 运行一次 Spring Boot 应用程序并退出

转载 作者:行者123 更新时间:2023-12-01 13:13:33 24 4
gpt4 key购买 nike

我有运行正常的 Spring Boot 应用程序。现在我想添加按需功能以从磁盘上的文件中导入一些数据(它将被使用一次,永远不会再次使用)。我有数据库连接、DTO 对象等可以使用,还有导入数据的方法。
我想启动我的应用程序,例如使用命令行开关(例如 -file path/to/file)。它应该启动一个应用程序,执行我的导入方法,然后关闭。
最好不要启动嵌入式 Tomcat。

我正在考虑使用 @SpringBootApplication 注释的单独主类,以及使用 -classpath 运行,但我不知道这是个好主意。

现在我认为最好制作一个小的独立项目,但也许有一个很好的功能,它允许我运行我的应用程序一次并执行导入方法。

最佳答案

您可以使用 Spring 的 CommandLineRunner接口(interface):

例如(取自 this guide ):

@SpringBootApplication
public class SpringBootConsoleApplication
implements CommandLineRunner {

private static Logger LOG = LoggerFactory
.getLogger(SpringBootConsoleApplication.class);

public static void main(String[] args) {
LOG.info("STARTING THE APPLICATION");
SpringApplication.run(SpringBootConsoleApplication.class, args);
LOG.info("APPLICATION FINISHED");
}

@Override
public void run(String... args) {
LOG.info("EXECUTING : command line runner");

for (int i = 0; i < args.length; ++i) {
LOG.info("args[{}]: {}", i, args[i]);
}
}
}

关于spring - 运行一次 Spring Boot 应用程序并退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com