[英]Run method from war application automatically after tomcat server startup
Project is a war using local tomcat 项目是一场使用本地雄猫的战争
I'm wondering how to run a method automatically after server startup? 我想知道服务器启动后如何自动运行方法? I know of ways to run it DURING server startup such as @Bean method or during context initialization, but how can I do it AFTER the server successfully starts? 我知道在服务器启动期间(例如@Bean方法)或在上下文初始化期间运行它的方法,但是在服务器成功启动后如何执行它呢?
On Tomcat, you can use the Tomcat-own LifecycleListener . 在Tomcat上,可以使用Tomcat自己的LifecycleListener 。 If you register a listener for the AFTER_START_EVENT on the host component, you should get what you want. 如果您在主机组件上注册了AFTER_START_EVENT的侦听器,则应获得所需的内容。
Code-Example of a LifecycleListener: LifecycleListener的代码示例:
package my.sourcecode;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
public class TomcatHostLifecycleListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent lifeCE) {
if (Lifecycle.AFTER_START_EVENT.equals(lifeCE.getType())) {
System.out.println("************ TomcatHostLifecycleListener: After Start Event");
}
}
}
The code must be be placed as JAR-File inside the global lib-folder of Tomcat! 必须将代码作为JAR文件放置在Tomcat的全局lib文件夹中!
A LifecycleListener has to be registerd in Tomcats server.xml , in your case inside the host element, because we want to listen to host startup: 您必须在Tomcats server.xml中 (在您的情况下)在host元素中注册一个LifecycleListener,因为我们要监听主机启动:
....
<Host ... >
<Listener className="my.sourcecode.TomcatHostLifecycleListener"/>
....
See Lifecycle-Doc for further documentation. 有关更多文档,请参见Lifecycle-Doc 。
(Tested with Tomcat 8.5.30 and Java 11) (已通过Tomcat 8.5.30和Java 11测试)
As I understood you are using Spring. 据我了解,您正在使用Spring。 So you can look on Spring application context events. 因此,您可以查看Spring应用程序上下文事件。 For example you can define event listener method like that 例如,您可以定义这样的事件侦听器方法
@EventListener
public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) {
System.out.println("Context Start Event received.");
}
使用Spring Boot,在方法中添加@PostConstruct批注会使它在Spring Boot应用程序启动后运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.