【问题标题】:Spring Boot synchronous launcherSpring Boot 同步启动器
【发布时间】:2015-02-26 22:50:48
【问题描述】:

org.springframework.boot.loader.Launcher 默认总是在 launch() 方法中产生一个后台线程 (https://github.com/spring-projects/spring-boot/blob/master/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java#L105)。是否有任何简单的方法可以将其更改为在同一线程中执行,以便我的服务启动器可以知道应用程序何时完全加载,而不是每次都立即成功退出。

【问题讨论】:

  • 看看它,您可以使用自己的实现,扩展 jarlauncher/warlauncher 类并覆盖启动方法。
  • 是的,我知道我可以轻松地覆盖该方法。问题是 spring-boot 不允许使用不同的 mainClass 作为 jar 启动方法。
  • 如果不生成新的Thread,则无法设置上下文类加载器,因此如果您尝试更改此方法,可能会遇到麻烦。您的“服务启动器”实际上在做什么?
  • 它是 Microsoft Windows 服务的启动器。默认情况下,它等待主方法完成以发出服务“UP”的信号 - 并且主方法中的任何异常(例如 spring 上下文启动失败)都会导致 java.exe 的退出代码 1,这将发出信号服务没有正常启动。由于线程分叉,我错过了这两件事。

标签: java spring spring-boot


【解决方案1】:

我相信你可以像这样注册监听器:

public static void main(String[] args) {
   SpringApplication app = new SpringApplication(WsBootClientApplication.class);

   app.addListeners(new ApplicationListener<ContextStartedEvent>() {
      @Override
      public void onApplicationEvent(ContextStartedEvent event) {
         //do your stuff
      }
   });
   app.run(args);
}

如果 ContextStartedEvent 不适合您,您可以将 ContextStartedEvent 替换为 ApplicationEvent。这更通用,将处理您的应用程序可以侦听的所有上下文生命周期事件。

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2020-08-04
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多