場景:
1. 配置了Spring和SpringMvc, Spring管理非Controller類的Bean, SpringMvc管理涉及的Controller類
2. web.xml已經配置了Spring的監聽器, SpringMvc的servlet映射
3. 包掃描配置正確
問題:
訪問指定的API鏈接,發現返回404, 日志顯示:"No mapping found for HTTP request with URI [/xxx.do] in DispatcherServlet with name 'xxx' ”
排查后發現:
SpringMvc除了org.springframework.web.servlet.DispatcherServlet之外,還需要配置兩個類:
(Spring 3.1之前的做法)
<!--配置注解控制器映射器,它是SpringMVC中用來將Request請求URL到映射到具體Controller--> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <!--配置注解控制器映射器,它是SpringMVC中用來將具體請求映射到具體方法--> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
(Spring3.1之后的做法)
<!--配置注解控制器映射器,它是SpringMVC中用來將Request請求URL到映射到具體Controller--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!--配置注解控制器映射器,它是SpringMVC中用來將具體請求映射到具體方法--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
還有一種簡便做法是在SpringMvc的配置文件中加入:<mvc:annotation-driven />
即可代替上面兩行配置
參考文章: SpringMVC和Spring的配置文件掃描包詳解 https://blog.csdn.net/uniqueweimeijun/article/details/72636481