Spring Aop之@Before、@After、@Around、@AfterReturning


在項目中使用到了@Aspect注解,故研究了下與其配套的幾個注解,將測試結果記錄下來

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class TestAspect {

    private static final Logger logger = LoggerFactory.getLogger(TestAspect.class);

    @Pointcut("execution(public * com.xwj.service..*.insert*(..))")
    private void recordLog() {

    }

    /**
     * 前置方法,在目標方法執行前執行
     * 
     * @param joinPoint
     */
    @Before("recordLog()")
    public void before(JoinPoint joinPoint) {
        logger.info("保存前方法:beforeSave");
    }

    /**
     * 后置方法,在目標方法執行后執行
     * 
     * @param joinPoint
     */
    @After("recordLog()")
    public void after(JoinPoint joinPoint) {
        logger.info("保存后方法:afterSave()");
    }

    @Around("recordLog()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        try {
            logger.info("around前");
            joinPoint.proceed();
            logger.info("around后");
        } catch (Throwable e) {
            logger.info("aop異常");
        }
        return obj;
    }

    @AfterReturning(returning = "retObj", pointcut = "recordLog()")
    public void doAfterReturning(Object retObj) throws Throwable {
        // 處理完請求,返回內容
        logger.info("返回值 : " + retObj);
    }

在上面代碼中,@Pointcut注解中execution表達式的意思就是com.xwj.service包下的所有子類中的以insert為前綴的方法

關於@Pointcut注解中,execution表達式的使用,可以參考AspectJ的切入點表達式---execution表達式詳解

發送請求,調用service中的insert方法,執行結果如下:

2018-04-16 08:54:49.610  INFO 2308 --- [nio-8080-exec-3] com.xwj.aop.TestAspect                   : around前
2018-04-16 08:54:49.610  INFO 2308 --- [nio-8080-exec-3] com.xwj.aop.TestAspect                   : 保存前方法:beforeSave
2018-04-16 08:54:49.627  INFO 2308 --- [nio-8080-exec-3] com.xwj.aop.TestAspect                   : around后
2018-04-16 08:54:49.627  INFO 2308 --- [nio-8080-exec-3] com.xwj.aop.TestAspect                   : 保存后方法:afterSave()
2018-04-16 08:54:49.627  INFO 2308 --- [nio-8080-exec-3] com.xwj.aop.TestAspect                   : 返回值 : null

通過打印出的結果可以看到,這幾個注解的執行順序:

  1、進入的是@Around中

  2、joinPoint.proceed()方法,進入到@Before

  3、@Before執行完后,又回到@Around

  4、@Around執行完后,進入到@After

  5、最后執行@AfterReturning

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM