javaspringservletsresin

Adding listener to servlet context in Spring


I am trying to use java config in spring 4 webmvc application. After surfing some examples in the Internet I have the following WebAppApplicationInitializer.

public class AppInit implements WebApplicationInitializer {
    private static final String CONFIG_LOCATION = "spring.examples.config";
    private static final String MAPPING_URL = "/rest/*";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        return context;
    }

It works fine in jetty, tomcat, but when I am using resin 4.0.40. web server show the following error:

java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml! at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:277) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at com.caucho.server.webapp.WebApp.fireContextInitializedEvent(WebApp.java:3777) at com.caucho.server.webapp.WebApp.startImpl(WebApp.java:3687) at com.caucho.server.webapp.WebApp.access$400(WebApp.java:207) at com.caucho.server.webapp.WebApp$StartupTask.run(WebApp.java:5234) at com.caucho.env.thread2.ResinThread2.runTasks(ResinThread2.java:173) at com.caucho.env.thread2.ResinThread2.run(ResinThread2.java:118)

When I comment this line

servletContext.addListener(new ContextLoaderListener(context));

all works fine.

Question is what is the purpose of adding listener to servlet context? Is it wrong not to add listener to servlet context?


Solution

  • The problem was the bug http://bugs.caucho.com/view.php?id=5611 in resin 4.0.40. ServletContextListener#contextInitialized() called twice. In resin 4.0.41 all works fine