Spring Boot:退出应用程序时发生异常 [英] Spring Boot: exception while exiting application

查看:483
本文介绍了Spring Boot:退出应用程序时发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个Spring应用程序,该应用程序在完成其工作后应退出.但是在我的实现中,我得到了一个例外.

I want to run a Spring application that should exit after it has done its work. But in my implementation I get an exception.

build.gradle包含:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
}

Application.java:

@SpringBootApplication
public class Application {

    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @PostConstruct
    public void doTheWorkAndExit() {
        // do the work ...
        SpringApplication.exit(context, () -> 0);
    }

}

我得到了例外

Exception thrown from LifecycleProcessor on context close

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.context.annotation.AnnotationConfigAppl
icationContext@1807f5a7: startup date [Fri Mar 11 10:03:27 CET 2016]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:415)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:975)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:934)
    at org.springframework.boot.SpringApplication.close(SpringApplication.java:1252)
    at org.springframework.boot.SpringApplication.exit(SpringApplication.java:1238)
    at mypackage.Application.doTheWorkAndExit(Application.java:34)
    ...

我该怎么办?有没有比使用System.exit(0)更好的解决方案?

What can I do? Is there a better solution than using System.exit(0)?

推荐答案

在您的Application.class中,您可以实现CommandLineRunner接口.

In your Application.class you can implement CommandLineRunner interface.

@SpringBootApplication
public class Application implements CommandLineRunner{}

实现后,您需要实现一个void方法run()

After implementation you need to implement a void method run()

@Override
public void run(String... strings) {
    //here starts your code (like in a normal main method in a java application)
}

执行完所有代码后,应用程序将关闭.

The application shuts down after excecuting all of the code.

完整的Application.class:

@SpringBootApplication
public class Application implements CommandLineRunner{

  @Override
  public void run(String... strings) {
      //here your code...
  }

  public static void main(String[] args) throws Exception {
      SpringApplication.run(Application.class, args);    
  }
}

这篇关于Spring Boot:退出应用程序时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆