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

    
    <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

你可能感兴趣的:(spring)