【问题标题】:Run Spring Boot application once and exit运行一次 Spring Boot 应用程序并退出
【发布时间】:2020-01-29 15:44:25
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    您可以为此使用 Spring 的 CommandLineRunner 接口:

    例如(取自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]);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我做了一些与 SpringBoot 和 JCommander 类似的附加操作,它使创建 CLI 应用程序变得非常容易,并且提供了比 CommandLineRunner 接口更多的附加功能。

      ->http://jcommander.org/

      【讨论】:

        猜你喜欢
        • 2021-01-05
        • 2019-04-28
        • 1970-01-01
        • 2017-02-18
        • 2019-06-04
        • 2017-09-19
        相关资源
        最近更新 更多