Spring-AOP的五種通知方式


AOP的五種通知方式:

前置通知:在我們執行目標方法之前運行(@Before

后置通知:在我們目標方法運行結束之后,不管有沒有異常(@After

返回通知:在我們的目標方法正常返回值后運行(@AfterReturning

異常通知:在我們的目標方法出現異常后運行(@AfterThrowing

環繞通知:目標方法的調用由環繞通知決定,即你可以決定是否調用目標方法,joinPoint.procced()就是執行目標方法的代碼 。環繞通知可以控制返回對象(@Around)

一、導jar包

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

二、在類路徑下建applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!--配置自動掃描的包-->
    <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>

    <!--配置自動為匹配aspectJ 注解的Java類生成代理對象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

三、接口

//接口
public interface ArithmeticCalculator {

    int add(int i, int j);

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);
}

四、實現類

package com.atguigu.spring.aop;

import org.springframework.stereotype.Component;

/**
 * @Author 謝軍帥
 * @Date2019/12/6 21:23
 * @Description
 */

//實現類
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
    @Override
    public int add(int i, int j) {
        int relust = i+j;
        return relust;
    }

    @Override
    public int sub(int i, int j) {
        int relust = i-j;
        return relust;
    }

    @Override
    public int mul(int i, int j) {
        int relust = i*j;
        return relust;
    }

    @Override
    public int div(int i, int j) {
        int relust = i/j;
        return relust;
    }
}

五、定義切面類

package com.atguigu.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author 謝軍帥
 * @Date2019/12/11 11:17
 * @Description
 */
@Component
@Aspect
public class LoggingAspect {
    /**
     * 在每一個接口的實現類的每一個方法開始之前執行一段代碼
     */

    @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        System.out.println("The method "+methodName+" begins with "+ Arrays.asList(args));
    }

    @After("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();

        System.out.println("The method "+methodName +" end......");
    }


    /**
     * 返回通知
     * 在方法正常結束后執行的代碼
     * 返回通知是可以訪問方法的返回值的!
     * @param joinPoint*/
     
    @AfterReturning(value = "execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))",
                    returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName +" end......result:"+result);
    }


    /**
     * 在目標方法出現異常時會執行的代碼
     * 可以訪問到異常對象,且可以指定在出現特定異常時在執行通知代碼
     * @param joinPoint
     * @param ex*/
     
    @AfterThrowing(value = "execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName +"occurs exception :" +ex);
    }

    /**
     * 環繞通知需要攜帶 ProceedingJoinPoint 類型的參數
     * 環繞通知類似於動態代理的全過程:ProceedingJoinPoint 類型的參數可以決定是否執行目標方法。
     * 且環繞通知必須有返回值,返回值即為目標方法的返回值
     * @param proceedingJoinPoint
     */
    /*@Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.* (..))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){

        Object result = null;
        String methodName = proceedingJoinPoint.getSignature().getName();

        try {
            //前置通知
            System.out.println("The method "+methodName+" begins with "+Arrays.asList(proceedingJoinPoint.getArgs()));
            //執行目標方法
            result = proceedingJoinPoint.proceed();

            //返回通知
            System.out.println("The method ends with "+result);
        } catch (Throwable e) {
            //異常通知
            System.out.println("The method occurs exception:"+e);

            throw new RuntimeException(e);
        }

        //后置通知
        System.out.println("The method "+methodName+" ends........");

        return result;
    }*/
}

六、測試

public class Test_aop {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) context.getBean("arithmeticCalculator");

        System.out.println(arithmeticCalculator.getClass().getName());

        int result = arithmeticCalculator.add(1,2);
        System.out.println("result:"+result);

        result = arithmeticCalculator.div(200,0);
        System.out.println("result:"+result);

    }
}


免責聲明!

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



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