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

时间:2014-10-12 19:50:53

标签: java spring spring-boot spring-data-cassandra

我正在使用Spring Boot构建一个命令行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,因为项目中没有其他内容。有谁知道为什么它会阻止线程在后台运行以阻止应用程序停止?

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

6 个答案:

答案 0 :(得分:25)

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

<div class="box one">1</div>
<div class="box two">2</div>

.box {
    font-size: 40px;
    margin: 5px;
    width: 300px;
    height: 150px;
}
.one{
    float: left;
    border: 5px solid rgba(255, 154, 188, 0.9);
    background-color: rgba(255, 165, 0, 0.25);
}
.two {
    position: relative;
    top: 170px;
    border: 5px solid rgba(35, 154, 255, 0.5);
    background-color: rgba(100, 165, 255, 0.25);
}

只需在运行时使用.close。

答案 1 :(得分:15)

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

答案 2 :(得分:8)

这是@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));
    }
}

答案 3 :(得分:5)

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

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

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

答案 4 :(得分:1)

使用org.springframework.boot.SpringApplication#exit。 E.g。

@Component
public class OneTimeRunner implements CommandLineRunner {

    @Autowired
    private ConfigurableApplicationContext context;

    @Override
    public void run(String... args) throws Exception { 
        SpringApplication.exit(context);
    }
}

答案 5 :(得分:0)

您可以尝试-

public void run(String... arg0) throws Exception {
int response = -1;
try {
    /*Do you job here and get a response code*/

    System.exit(response); //success response

} catch (Exception e) {
    System.exit(response); //failure response
}
}
相关问题