spring aop 如何切面到mvc 的controller

网上搜罗半天,不知道什么原因,看了源码,好像他们说的controller 是不受代理的,也对哈,不知道怎么办,于是在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. 


这个人说的好像很对啊。我把aspectj 和springmvc的配置文件放到一起就可以用到controller上了。 

spring-mvc.xml 

Java代码   收藏代码
  1. <context:component-scan base-package="com.cms.controller" />  
  2. <context:component-scan base-package="com.cms.aspectj" />  
  3. <!-- <bean id="sysLogAspectJ" class="com.cms.aspectj.SysLogAspectJ" /> -->  
  4. <aop:aspectj-autoproxy proxy-target-class="true">  
  5. <!--     <aop:include name="sysLogAspectJ" /> -->  
  6. </aop:aspectj-autoproxy>  
  7. <!-- <mvc:annotation-driven /> -->  
  8. <bean  
  9.     class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />  
  10. <bean  
  11.     class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />  
sysLogAspectJ 

Java代码   收藏代码
  1. package com.cms.aspectj;  
  2.   
  3. import org.aspectj.lang.ProceedingJoinPoint;  
  4. import org.aspectj.lang.annotation.Around;  
  5. import org.aspectj.lang.annotation.Aspect;  
  6. import org.aspectj.lang.annotation.Pointcut;  
  7. import org.springframework.stereotype.Component;  
  8.   
  9. @Component  
  10. @Aspect   
  11. public class SysLogAspectJ {  
  12.   
  13.     @Pointcut("within(@org.springframework.stereotype.Controller *)")  
  14.     public void cutController(){  
  15.           
  16.     }  
  17.       
  18.     @Around("cutController()")  
  19.     public Object recordSysLog(ProceedingJoinPoint point) throws Throwable{  
  20.         System.out.println("lfkdjj================================================================");  
  21.         return point.proceed();  
  22.     }  
  23.       
  24.       
  25.       
  26. }  

转载于:https://my.oschina.net/u/140213/blog/166985

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值