有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何关闭Spring引导命令行应用程序

我正在使用SpringBoot构建一个命令行java应用程序,以使其快速工作

应用程序加载不同类型的文件(例如CSV)并将其加载到Cassandra数据库中。它不使用任何web组件,也不是web应用程序

我遇到的问题是在工作完成后停止应用程序。我使用带有@Component的Spring CommandLineRunner接口来运行任务,如下所示,但是当工作完成时,应用程序没有停止,它由于某种原因一直在运行,我找不到停止它的方法

@Component
public class OneTimeRunner implements CommandLineRunner {

    @Autowired
    private CassandraOperations cassandra;

    @Autowired
    private ConfigurableApplicationContext context;

    @Override
    public void run(String... args) throws Exception {
        // do some work here and then quit
        context.close();
    }
}

更新:问题似乎是spring-cassandra,因为项目中没有其他内容。有人知道为什么它让线程在后台运行以阻止应用程序停止吗

更新:通过更新到最新的spring启动版本,问题消失了


共 (5) 个答案

  1. # 1 楼答案

    这是@EliuX答案与@Quan Vo答案的组合。谢谢你们两位

    主要的不同是我通过了Spring应用程序。退出(上下文)响应代码作为系统参数。exit()因此,如果关闭Spring上下文时出错,您会注意到

    Spring应用程序。exit()将关闭Spring上下文

    系统。exit()将关闭应用程序

    @Component
    public class OneTimeRunner implements CommandLineRunner {
    
        @Autowired
        private ConfigurableApplicationContext context;
    
        @Override
        public void run(String... args) throws Exception { 
           System.exit(SpringApplication.exit(context));
        }
    }
    
  2. # 2 楼答案

    我找到了解决办法。您可以使用以下选项:

    public static void main(String[] args) {
        SpringApplication.run(RsscollectorApplication.class, args).close();
        System.out.println("done");
    }
    

    只需在运行时使用.close()

  3. # 3 楼答案

    使用org.springframework.boot.SpringApplication#exit。例如

    @Component
    public class OneTimeRunner implements CommandLineRunner {
    
        @Autowired
        private ConfigurableApplicationContext context;
    
        @Override
        public void run(String... args) throws Exception { 
            SpringApplication.exit(context);
        }
    }
    
  4. # 4 楼答案

    答案取决于仍在工作的是什么。您可能可以通过线程转储(例如使用jstack)来发现这一点。但是如果它是由Spring启动的,那么您应该能够使用ConfigurableApplicationContext.close()在main()方法(或CommandLineRunner)中停止应用程序

  5. # 5 楼答案

    我在当前的项目(SpringBoot应用程序)中也遇到了这个问题。 我的解决办法是:

    // releasing all resources
    ((ConfigurableApplicationContext) ctx).close();
    // Close application
    System.exit(0);
    

    context.close()不要停止我们的控制台应用程序,它只是在释放资源