Ant*_*eda 2 logging app-startup spring-boot
为了能够验证我们的Spring Boot应用程序的启动和关闭能力,我们希望配置一个startup.log和shutdown.log捕获事件来引导和关闭该应用程序。
对于启动,所有内容最多:
Root WebApplicationContext: initialization completed in {x} ms
Run Code Online (Sandbox Code Playgroud)
要关闭所有内容,请执行以下操作:
Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@53bd8fca: startup date [Wed Aug 19 09:47:10 PDT 2015]; root of context hierarchy
Run Code Online (Sandbox Code Playgroud)
到最后。
这是特定于容器的东西吗?(Tomcat vs码头vs Undertow)
我们使用@PostConstruct和@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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将EventListener与ApplicationReadyEvent和ContextStoppedEvent结合使用。
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
}
}
Run Code Online (Sandbox Code Playgroud)
注意:Stephane Nicoll 提供的答案确实包含相同(正确)的信息,但我想提供一个有效的 Java 示例。
您可以创建一个事件侦听器手表ApplicationReadyEvent和ContextStoppedEvent任何你想要的和日志。
@Service
public class Foo {
@EventListener
public void onStartup(ApplicationReadyEvent event) { ... }
@EventListener
public void onShutdown(ContextStoppedEvent event) { .... }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3557 次 |
| 最近记录: |