简体   繁体   中英

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?

On Tomcat, you can use the Tomcat-own LifecycleListener . If you register a listener for the AFTER_START_EVENT on the host component, you should get what you want.

Code-Example of a 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!

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:

....
<Host ... >
    <Listener className="my.sourcecode.TomcatHostLifecycleListener"/>
    ....

See Lifecycle-Doc for further documentation.

(Tested with Tomcat 8.5.30 and Java 11)

As I understood you are using Spring. So you can look on Spring application context events. 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应用程序启动后运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM