使用 aop攔截 springMVC的controller並獲取請求引數及返回結果
有人說使用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 註解