---
title: "拦截器与<mvc:annotation-driven />冲突解决"
author: "xj84"
date: "2014-05-13T10:47:23Z"
tags: []
categories: ["编程语言"]
slug: "mvc-annotation-driven"
draft: false
lastmod: "2014-05-13T10:47:23Z"
id: 2065681
url: "https://xj84.iteye.com/blog/2065681"
---

当不配置&lt;mvc:annotation-driven&gt; 时：

 

&lt;!-- 自动扫描com.yunos.controller下的@controller注解的类 --&gt;

&lt;context:component-scan base-package="com.yunos.controller" /&gt;

 

&lt;bean id="logInterceptor" class="com.yunos.interceptor.LogInterceptor" /&gt;

 

&lt;!-- 为controller增加拦截器logInterceptor --&gt;

&lt;bean

class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;

&lt;property name="interceptors"&gt;

&lt;list&gt;

&lt;ref bean="logInterceptor" /&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

 

&lt;!-- 重写AnnotationMethodHandlerAdapter，为controller方法增加入参user --&gt;

&lt;bean

class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;

&lt;property name="customArgumentResolvers"&gt;

&lt;list&gt;

&lt;bean class="com.yunos.resolver.UserArgumentResolver"&gt;&lt;/bean&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

 

当xml文件中使用了&lt;mvc:annotation-driven /&gt;时，需修改为如下定义，否则，拦截器失效：

&lt;!-- 自动扫描com.yunos.controller下的@controller注解的类 --&gt;

&lt;context:component-scan base-package="com.yunos.controller" /&gt;

&lt;!-- 当使用&lt;mvc:annotation-driven /&gt;时，要用下面这种方法声明拦截器 --&gt;

&lt;mvc:interceptors&gt;

&lt;mvc:interceptor&gt;

&lt;mvc:mapping path="/\*\*" /&gt;

&lt;bean class="com.yunos.interceptor.LogInterceptor" /&gt;

&lt;/mvc:interceptor&gt;

&lt;/mvc:interceptors&gt;

&lt;!-- 当使用&lt;mvc:annotation-driven /&gt;时，要用下面这种方法声明拦截器AnnotationMethodHandlerAdapter --&gt;

&lt;mvc:annotation-driven&gt;

&lt;mvc:argument-resolvers&gt;

&lt;bean class="com.yunos.resolver.UserArgumentResolver" /&gt;

&lt;/mvc:argument-resolvers&gt;

&lt;/mvc:annotation-driven&gt;

&lt;!-- 使用validate验证需要声明 --&gt;

&lt;mvc:annotation-driven /&gt;