运行 Spring Boot 应用程序一次并退出 [英] Run Spring Boot application once and exit

查看:73
本文介绍了运行 Spring Boot 应用程序一次并退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have Spring Boot application which works ok. Now I want to add on-demand feature to import some data from file on disc (it'll be used once and never again). I have database connection, DTO objects etc ready to use, also the method to import data. I would like to start my application, for example with command line switch (for example -file path/to/file). It should make an app start, execute my import method, and shutdown. The best would be not to start embedded Tomcat.

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

I was thinking about separate main class annotated @SpringBootApplication, and about running with -classpath, but I don't know it's good idea.

现在我觉得做一个小的分离项目更好,但也许有一个很好的功能,它允许我运行我的应用程序一次并执行导入方法.

Now I think it's better to make small separated project, but maybe there's a nice feature, which allow me to run my app once and execute import method.

推荐答案

你可以使用 Spring 的 CommandLineRunner 接口:

you can use Spring's CommandLineRunner interface for that:

例如(摘自本指南):

@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 Boot 应用程序一次并退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆