Spring MVC下对Controller 的AOP切面

来源:互联网 发布:learning python中文版 编辑:程序博客网 时间:2024/06/05 08:31
在使用spring mvc采用@Controller注解时,对Controller进行Aop拦截不起作用,原因是该注解的Controller已被spring容器内部代理了.
Spring MVC加载的是WebApplicationContext而不是ApplicationContext,问题就在这,应该把schema和加载加到 spring-mvc.xml,也就是

WebApplicationContext.xml中。

1.添加配置如下:

 <aop:config>
<aop:aspect id="serviceAop" ref="aaa">
<aop:pointcut id="servicePointCut"
expression="execution(* com.controller.*.*(..))" />
<aop:around pointcut-ref="servicePointCut" method="doArount" />
</aop:aspect>
</aop:config>
<bean id="aaa" class="com.ControllerProxy">
</bean>



以 <aop:pointcut id="serviceMethod" expression="execution(* *..*Service.*(..))" />为例讲解

首先:这个表达式是分为4块的,即:方法返回类型 包 +(子包)+ 方法名 + 参数个数或者类型

1、第一个 * 表示:对任意的返回类型方法进行匹配

2、第二个 * 表示:  对任意的包并且包的最后是以Service结尾的包

3、第三个 * 表示:  对任意的方法名进行匹配

 4、第四个(..)表示: 通配,即方法中可以有0个或者多个参数,如果想执行参数为2个,即(*, String)表示2个参数,第二个参数为String类型。



2. aop类如下:

public class ControllerProxy {

public Object doArount(ProceedingJoinPoint point) throws Throwable {
// 返回对象
Object ret = null;
// 获得返回对象类型
Signature signature = point.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
String className = methodSignature.getDeclaringType().getSimpleName();
String methodName = method.getName();
       ......
return ret;
}

0 0