Search code examples
springservletsspring-mvcinitializationstartup

Spring Web Application: Post-DispatcherServlet initialization


I am using Spring 3.2 DispatcherServlet. I am looking for an initialization hook that takes place after the DispatcherServlet initialization completes; either a standard Spring solution or servlet solution. Any suggestions?

As a point of reference, the final logging statements after servlet startup follow. I want my initialization method to execute right after the configured successfully log statement.

DEBUG o.s.w.s.DispatcherServlet - Published WebApplicationContext of servlet 'mySpringDispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.mySpringDispatcherServlet] 
INFO  o.s.w.s.DispatcherServlet - FrameworkServlet 'mySpringDispatcherServlet': initialization completed in 5000 ms   
DEBUG o.s.w.s.DispatcherServlet - Servlet 'mySpringDispatcherServlet' configured successfully 

From my research, so far the following have not had the desired effect:

  1. Extending ContextLoaderListener/implementing ServletContextListener per this answer.
  2. Implementing WebApplicationInitializer per the javaoc.
  3. My beans use @PostConstruct successfully; I'm looking for a Servlet or container level hook that will be executed essentially after the container initializes and post-processes the beans.

Solution

  • The root issue was that I couldn't override the final method HttpsServlet.init(). I found a nearby @Override-able method in DispatcherServlet.initWebApplicationContext that ensured my beans and context were fully initialized:

    @Override
    protected WebApplicationContext initWebApplicationContext()
    {
        WebApplicationContext wac = super.initWebApplicationContext();
    
        // do stuff with initialized Foo beans via:
        // wac.getBean(Foo.class);
    
        return result;
    }