Spring AOP代理Controller层

基础学的不扎实,面试时被虐惨了..回来狂抓基础了..
看到spring Aop这块想优化下以前项目的代码,网上看了半天,各种案例,试了又试,没什么效果,说扫描包第一次扫描后,第二次就不会扫描了,所以Aop不会起效..(熟悉Jvm会懂的..)
网上寻它千百度,重要在google搜素时看到个提问,试试了下有用!(在这里不得不吐糟下百度了..)
http://stackoverflow.com/questions/17834958/spring-aop-is-not-working-in-with-mvc-structure?rq=1

1.aspectj:

package com.qfmyy.aspcetj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogAspcetj {
    @Pointcut("within(@org.springframework.stereotype.Controller *)")
    public void cutController() {

    }

    @Before(value = "cutController()")
    public void doAccessCheck() {
        System.out.println("前置通知");
    }

    @After(value = "cutController()")
    public void after() {
        System.out.println("最终通知");
    }

    @AfterReturning(value = "cutController()")
    public void doAfter() {
        System.out.println("后置通知");
    }

    @AfterThrowing(value = "cutController()")
    public void doAfterThrow() {
        System.out.println("例外通知");
    }

    @Around(value = "cutController()")
    public Object doBasicProfiling(ProceedingJoinPoint point) throws Throwable {

        System.out.println("进入环绕通知");
        Object result = point.proceed();
        System.out.println("退出方法");

        return result;
    }
}

2.spring-context.xml

    <!-- 使用Annotation扫描@controller -->
    <context:component-scan base-package="com.annotation"
        use-default-filters="false">
        <!-- 多个用,分割 -->
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <context:component-scan base-package="com.qfmyy.aspcetj" />

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

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

源码:https://github.com/YiQiuFengYe/springAop-Controller

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值