Bitmap
Bitmap

Reputation: 12538

Tomcat after Startup Event with spring

I have a function I want to execute straight after tomcat has started and loaded all its attributes successfully. I don't want to use ServletContextListener as this will require the function to start before tomcat starts. Can someone suggest how to go about this?

Upvotes: 3

Views: 9985

Answers (3)

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

I think JMX Tomcat supports can meet your requirement, even no ServletContextListener is deployed in container.

Upvotes: 0

Zeki
Zeki

Reputation: 5277

You could create a startup servlet and then add that to the end of your web.xml:

<servlet>
        <servlet-name>StartupServlet</servlet-name>
        <servlet-class>com.your.package.MyStartupServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>


public class MyStartupServlet extends HttpServlet {

    public void init(ServletConfig config) throws ServletException {
        try {
             //  Startup code here
        } catch (Exception e){
            // Log exception
        }
    }

    public java.lang.String getServletInfo() {
        return "StartupServlet";
    }
}

Upvotes: 0

Bozho
Bozho

Reputation: 597116

ServletContextListener.contextInitialized(..) is the method that is called after all servlets and filters have initialized for a given application.

  • if there are multiple ServletContextListeners, some of them are called before the others (logically)
  • if there are multiple applications (hence multiple contexts) some of them are started before others.

Update I will now assume your setup, although you didn't share it:

  • you start spring via a listener (and not with a servlet)
  • you configure hibernate within spring

In that case, you have two options:

  • define your ServletContextListener after the one for spring in web.xml, thus guaranteeing it will be invoked after it
  • use spring's lifecycle processor

Upvotes: 7

Related Questions