Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultAnnotationHandlerMapping via ContextLoaderListener instead of DispatcherServlet on Spring 3

Tags:

java

spring

When I use DispatcherServlet, I get a java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? error when I use a DelegatingFilterProxy filter. Therefore I've removed the DispatcherServlet and now I use a ContextLoaderListener instead, and my Spring application loads fine. However, I have a problem with one VERY important bean:

   <context:component-scan base-package="com.mydomain"/>  
   <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
      <property name="interceptors">
         <list>
            <ref bean="openSessionInViewInterceptor" />
         </list>
      </property>
   </bean>

This bean no longer works, none of my @Controller's are URL mapped anymore. If I switch back to using DispatcherServlet, no problem (except that my filter is useless again). How can I get this bean to load correctly from within a ContextLoaderListener?

Cheers

Nik

like image 361
niklassaers Avatar asked Sep 23 '09 09:09

niklassaers


1 Answers

You need both the ContextLoaderListener and the DispatcherServlet - the error message didn't tell you to remove the servlet.

To clarify what Spring is doing here, the DispatcherServlet creates its own ApplicationContext (typically using xxx-servlet.xml), but any Spring Filters that you configure in web.xml don't have access to the servlet's ApplicationContext.

The ContextLoaderListener creates a second ApplicationContext (associated with the whole webapp), and links itself with the servlet's ApplicationContext, allowing filters and servlets to communicate via Spring.

like image 184
skaffman Avatar answered Sep 22 '22 04:09

skaffman