您的位置:首页 > 编程语言 > Java开发

使用 aop拦截 springMVC的controller并获取请求参数及返回结果

2016-06-08 15:16 736 查看
有人说使用aop拦截不到springMVC的controller,一般出现此种情况大多是由于配置错误造成,不废话直接进入主题:

1、applicationContext.xml 配置扫描 除@controller外的bean

<context:component-scan base-package="XXX" scoped-proxy="targetClass">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

2、 applicationContext-mvc.xml 配置扫描 @controller bean

<mvc:annotation-driven />
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="xxxxx.controller" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

3、编写 aop相关bean

①、拦截指定方法

@Pointcut("execution(* XXX.gatewayDelFromUser(..))")
public void deleGateway(){

}
@AfterReturning(pointcut ="deleGateway() && args(req,request)",returning="result")
public void afterReturnExcute(GatewayDelFromUserRequestMsg req,HttpServletRequest request,
BaseResponseMsg result) {
logger.info   ("*******************************respMsg is :[{}],the result[{}]",req,result);
}

注意:此处args中的参数个数需要与拦截的方法个数相同,否则会拦截不到

②、自定义注解

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.METHOD})

public @interface AttributeChange {
String value() default "";

}

@Pointcut("@annotation(com.sengled.cloud.zigbee.aop.openapi.AttributeChange)")
public void arrChange(){
}

@Before("arrChange() && args(message)")
public void beforExcute(Object message) {

}

在需要拦截的方法上添加  @AttributeChange 注解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: