Artanis
Artanis

Reputation: 631

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?

Upvotes: 0

Views: 1921

Answers (3)

Artanis
Artanis

Reputation: 631

Using Spring Boot, adding the @PostConstruct annotation to the method causes it to run after the Spring Boot application starts up.

Upvotes: 1

VinZ
VinZ

Reputation: 444

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)

Upvotes: 2

Dmitry Margolis
Dmitry Margolis

Reputation: 142

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.");
}

Upvotes: 1

Related Questions