问题
Ok I understand the fact that any web application context configured through DispatcherServlet inherits all the beans already defined in the root WebApplicationContext. Nevertheless i have configured some interceptors in my root ApplicationContext
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="2"/>
<property name="interceptors">
<list>
<ref bean="statisticsInterceptor"/>
<ref bean="sessionDiagnosticsInterceptor"/>
...
Then in my web.xml I have something like this:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext*.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcher-api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appOtherContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher-api</servlet-name>
<url-pattern>/example/apiOther/*</url-pattern>
</servlet-mapping>
So the problem I have is that every time I go to any URL that contains "/example/apiOther/", the Interceptors will not be reached/run. My question is: WHY? What is the scope of the handlerMapping? I thought that because it is in the root applicationContext it should apply to all child contexts. I've been doing some research and I think that HandlerMappings are limited to its context even if it is the root Context. Is that right?
回答1:
As you configure your interceptors through DefaultAnnotationHandlerMapping
, they will be used only for controllers in same ApplicationContext. You can (even it is not very nice) declare the interceptors in root application context, provided the DefaultAnnotationHandlerMapping
that referes to them is declared in servlet application context where you declare your controllers, either directly or through annotations.
来源:https://stackoverflow.com/questions/26306420/spring-interceptors-configured-in-root-applicationcontext-cannot-be-reached-from