Recently, I've reapackaged my java spring application to become a WAR file for deployment in tomcat. After some testing I noticed, that public static void main(String[] args)
is not executed. Some necessary initialization of my application is done in main
. Is there something like a main
method in a WAR file? What is the appropiate place in a WAR file to run some initialization?
You can add a listener to your web.xml
file:
<listener>
<description>Application startup and shutdown events</description>
<display-name>Test</display-name>
<listener-class>com.package.package.StartClass</listener-class>
</listener>
public class StartClass implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//Context destroyed code here
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
//Context initialized code here
}
}
Well, You will have to create a listener in your web.xml that will be invoked by container at the time of startup.
<listener>
<listener-class>com.rdv.example.WebAppContext</listener-class>
</listener>
And this class will be implementing ServletContextListener
public class WebAppContext implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
// Do your processing that you are trying to do in main method.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With