4

为了能够验证 Spring Boot 应用程序的启动和关闭,我们希望配置一个 startup.log 和 shutdown.log 捕获启动和关闭应用程序的事件。

为了启动一切:

Root WebApplicationContext: initialization completed in {x} ms

并从以下位置关闭所有内容:

Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@53bd8fca: startup date [Wed Aug 19 09:47:10 PDT 2015]; root of context hierarchy

到最后。

这是特定于容器的东西吗?(Tomcat vs Jetty vs Undertow)

4

3 回答 3

7

您可以创建一个事件侦听器来监视ApplicationReadyEventContextStoppedEvent记录您想要的任何内容。

@Service
public class Foo {

    @EventListener
    public void onStartup(ApplicationReadyEvent event) { ... }

    @EventListener
    public void onShutdown(ContextStoppedEvent event) { .... }

}
于 2015-08-20T05:48:37.380 回答
4

我们使用@PostConstructand@PreDestroy来记录启动和关闭:

package hello;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    @PostConstruct
    public void startupApplication() {
        // log startup
    }

    @PreDestroy
    public void shutdownApplication() {
        // log shutdown
    }

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

}
于 2018-07-06T07:14:35.020 回答
3

您可以将EventListenerApplicationReadyEventContextStoppedEvent结合使用。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
class StartupShutdownEventListener {

  @EventListener
  void onStartup(ApplicationReadyEvent event) {
    // do sth
  }

  @EventListener
  void onShutdown(ContextStoppedEvent event) {
    // do sth
  }
}

注意:Stephane Nicoll 提供的答案确实包含相同(正确)的信息,但我想提供一个有效的 Java 示例。

于 2017-02-15T12:57:54.333 回答