Add a class inside the JAR with the following code:
public class TomcatStartupListener implements org.apache.catalina.LifecycleListener { public void lifecycleEvent(org.apache.catalina.LifecycleEvent event) { if (event.getType().equals("after_start")) {
Note. To compile this, you need to add <tomcat-dir>/lib/catalina.jar to your classpath. Otherwise, during compilation, he will not be able to find the necessary interfaces ( org.apache.catalina.LifecycleListener and org.apache.catalina.LifecycleEvent ). Once you are done compiling, put the JAR as usual in <tomcat-dir>/lib .
Now open <tomcat-dir>/conf/server.xml and add the following to the <Server> section:
<Listener className="com.yourpackage.TomcatStartupListener" />
Now that your Tomcat server is starting up, this TomcatStartupListener class inside your JAR will be called, and you can call your main method. There are also many other types of events! You can use any of these types of events:
- before_init
- after_init
- before_start
- configure_start
- start
- after_start
- before_stop
- stop
- configure_stop
- after_stop
- before_destroy
- after_destroy
This approach is necessary because of the way class loaders work in Tomcat (or even most JVMs). Here are the important points from this link:
There are three aspects of a class loader behavior Lazy Loading Class Caching Separate Namespaces
The JVM will be very difficult if all classes inside all JARs load indiscriminately. Thus, classes inside shared JARs are only loaded on demand. The only way to invoke the main method is to add the above lifecycle listener.
Subhas
source share