使用 aop拦截 springMVC的controller并获取

2019-07-09  本文已影响0人  不知名的蛋挞

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

<context:component-scan base-package="com.abc">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

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

<aop:aspectj-autoproxy proxy-target-class="true"/>

<!--scan all @Controller class only-->
<context:component-scan base-package="com.abc.web" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

3、编写 aop相关bean

① 拦截指定方法

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

@Around("pointcut()")
public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
        // do sth
}

② 自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SqlDebug {
}
@Around("@annotation(com.abc.web.aop.SqlDebug)")
public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
        // do sth
}

在需要拦截的方法上添加 @SqlDebug 注解

上一篇 下一篇

猜你喜欢

热点阅读