如何关闭Spring Boot命令行应用程序

ESa*_*ala 28 java spring spring-boot spring-data-cassandra

我正在使用Spring Boot构建一个Command Line java应用程序,以使其快速运行.

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

我遇到的问题是在工作完成后停止应用程序.我使用Spring CommandLineRunner接口@Component来运行任务,如下所示,但是当工作完成后,应用程序不会停止,它会因某种原因而继续运行,我找不到阻止它的方法.

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

更新:更新到最新的春季启动版本后问题消失了.

ACV*_*ACV 28

我找到了解决方案.你可以用这个:

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

只需在运行时使用.close.


Dav*_*yer 15

答案取决于仍然在做什么.你可以找到一个线程转储(例如使用jstack).但是,如果它是由Spring启动的任何东西,你应该可以用来ConfigurableApplicationContext.close()在main()方法(或在CommandLineRunner)中停止应用程序.


Abe*_*ROS 10

这是@EliuX回答与@Quan Vo的结合.谢谢你们俩!

主要的不同是我将SpringApplication.exit(context)响应代码作为参数传递给System.exit(),因此如果关闭Spring上下文时出现错误,您会注意到.

SpringApplication.exit()将关闭Spring上下文.

System.exit()将关闭应用程序.

@Component
public class OneTimeRunner implements CommandLineRunner {

    @Autowired
    private ConfigurableApplicationContext context;

    @Override
    public void run(String... args) throws Exception { 
       System.exit(SpringApplication.exit(context));
    }
}
Run Code Online (Sandbox Code Playgroud)


Qua*_* Vo 5

我在当前项目(spring boot应用程序)中也遇到了这个问题.我的解决方案是:

// releasing all resources
((ConfigurableApplicationContext) ctx).close();
// Close application
System.exit(0);
Run Code Online (Sandbox Code Playgroud)

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


Eli*_*iuX 5

使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)