Aop有的人说拦截不到Controller。有的人说想拦截到Controller必须得拦截org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter。。。今天,我们就来细细分析一下。

首先Aop可以拦截到Controller的,这个是毋容置疑的;其次须拦截AnnotationMethodHandlerAdapter也不是必须的。造成aop无法拦截controller,主要是因为声明aop的配置写到了applicationContext.xml中。看了一下国外的帖子:(http://stackoverflow.com/questions/17834958/spring-aop-is-not-working-in-with-mvc-structure?rq=1)

<context:component-scan base-package="com.dao" /> 
<mvc:annotation-driven/> 

<aop:aspectj-autoproxy />   
from application-context.xml to controller-servlet.xml? 

The aspects and the beans to be applied needs to be in the same ApplicationContext but ApplicationContext is not aware of WebApplicationContext . 

Indeed your controller (annotated by @Controller) and your aspects (annotated by @Aspect) should be in the same Spring context. 

Usually people define their controllers in the dispatch-servlet.xml or xxx-servlet.xml and their service beans (including the aspects) in the main applicationContext.xml. It will not work. 

When Spring initializes the MVC context, it will create a proxy for your controller but if your aspects are not in the same context, Spring will not create interceptors for them. 

大概是说,applicationContext.xml和servlet.xml都有各自的上下文(看论坛上的说法貌似是这样的)。所以在Controller上AOP,需要把AOP配置写在servlet.xml里,也就是定义到spring-mvc.xml里。