49

我正在使用 Spring Boot 构建一个命令行 java 应用程序以使其快速运行。

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

我遇到的问题是在工作完成后停止应用程序。我正在使用带有 a 的 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();
    }
}

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

更新:通过更新到最新的 Spring Boot 版本,问题消失了。

4

5 回答 5

47

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

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

只是.close()在运行时使用。

于 2015-09-01T20:04:27.307 回答
26

答案取决于仍在工作的是什么。您可能可以通过线程转储找到答案(例如使用 jstack)。但是如果它是由 Spring 启动的任何东西,您应该能够ConfigurableApplicationContext.close()在您的 main() 方法(或在CommandLineRunner.

于 2014-10-12T20:44:23.483 回答
21

这是@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));
    }
}
于 2017-08-08T12:42:46.973 回答
5

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

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

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

于 2015-10-14T09:31:56.460 回答
4

使用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);
    }
}
于 2017-06-21T19:57:46.287 回答