---
title: "正确配置spring aop，在controller中使用AOP"
author: "usherlight"
date: "2011-12-12T12:04:51Z"
tags: []
categories: ["Web前端"]
slug: "spring-aop-controller-aop"
draft: false
lastmod: "2011-12-12T12:05:39Z"
id: 1306111
url: "https://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.**<span style="color:darkred">关键步骤来了：这个文件也要加入<aop:aspectj-autoproxy proxy-target-class="true"/>， 一定要添加proxy-target-class="true"</span>**！ 这是用于通知spring使用cglib而不是jdk的来生成代理方法。
    c. 另外一个事项，controller需要使用@controller注释，而不是继承abstract controller。
    d. 建议使用aspectj来完成aop