[英]Run a method after Tomcat server starts
只有在 Tomcat 服務器啟動並運行后,我才需要啟動/運行方法(在類中聲明的 3 個方法)。 我瀏覽了幾個線程,建議在web.xml
使用Servlet
s(偵聽器類)。 問題是我的實現ServletContextListene
r 的類甚至在加載 Tomcat 服務器完成之前運行。
注意:我的web.xml
已被標記為調度程序 servlet,以查找任何 REST API 調用。
例如(以下是一些日志以幫助您了解更多信息):
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 26, 2018 6:20:43 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
.
{{ Connect with MYSQL }}
.
Oct 26, 2018 6:20:50 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
.
18:20:51.394 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/user/someMethod],methods=[POST],produces=[application/xml || application/json]}" onto public java.util.ArrayList<com.x.y.z.User> com.z.y.controllers.UserController.deleteUser(com.x.y.z.User)
18:20:52.090 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Fri Oct 26 18:20:50 IST 2018]; parent: Root WebApplicationContext
18:20:52.181 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Fri Oct 26 18:20:50 IST 2018]; parent: Root WebApplicationContext
18:20:52.394 [localhost-startStop-1] INFO o.s.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 2041 ms
Oct 26, 2018 6:20:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8081"]
Oct 26, 2018 6:20:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8010"]
Oct 26, 2018 6:20:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 27236 ms
{{ I want to call methods after Tomcat starts }}
當我在ServletContextListener
下初始化類時,下面的日志會拋出。
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 26, 2018 6:22:09 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
.
.
{{ Connect with MYSQL }}
.
18:22:16.461 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 6635 ms
**MyClass - myFileWatcher()
The above thread has started**
.
.
由於我的方法有線程,它甚至在 Tomcat 完全啟動之前就卡住了(只有當顯示“信息:服務器啟動時間為 27236 毫秒”時,線程才應啟動)。
注意:如果我錯過了什么,請告訴我。
您可以編寫一個提供CommandLineRunner
的@Bean
。 像這樣的事情:
@Bean
public CommandLineRunner commandLineRunner(SomeAppService someAppService) {
return strings -> {
// do something with someAppService
// this code will run just after the application has fully started
};
}
還有其他方法可以做到這一點。 你可以在這里閱讀一些相關的文章:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.