在Controller中使用AOP

转:http://usherlight.iteye.com/blog/1306111

 

在Controller中使用AOP的问题主要在于如何让Controller能够被检测到。 
Controller和其他Spring bean的区别在于:Controller是由mvc定义并在web.xml中的dispatcher中定义的。 

解决方法: 
1、正确定义Controller,(比较通用的做法,没有特殊情况的话,大部分应用没有这个问题) 
    a. 将服务层的类都放在ApplicationCotext-*.xml中定义,在context listener中初始化(注意,任何Controller都不应该在这里出现),要包括<aop:aspectj-autoproxy/>, 在这里,有没有proxy-target-class="true" 没有关系(具体含义参看下文) 
    b. 定义mvc的配置文件,一般是 <<servlet name>>-servlet.xml,一般(也是推荐做法)使用auto scan来定义所有的Controller.关键步骤来了:这个文件也要加入<aop:aspectj-autoproxy proxy-target-class="true"/>, 一定要添加proxy-target-class="true"! 这是用于通知Spring使用cglib而不是jdk的来生成代理方法。 
    c. 另外一个事项,Controller需要使用@Controller注释,而不是继承abstract Controller。 
    d. 建议使用aspectj来完成aop 

posted @ 2015-06-26 11:39  风真天  阅读(550)  评论(0编辑  收藏  举报