Day15AOP終章

  • aop:point-cut標簽指定了切點,返回值、包、類、方法與參數(shù),只匹配符合條件的方法,也就是對這些方法進行代理,條件可以進行與或非操作,分別使用and或&&、or或||、!進行多條件匹配。
  • aop:before標簽是前置通知,在切點方法執(zhí)行前通知
  • aop:around標簽是環(huán)繞通知,在方法執(zhí)行前后都通知
  • aop:after標簽是后置通知,在方法執(zhí)行后通知
  • aop:after-returning標簽是后置返回通知,方法執(zhí)行后的返回值進行通知,returning參數(shù)所對應的值是方法返回的參數(shù)用于放在method方法中的形參。
  • aop:after-throwing是異常拋出通知,只有方法的執(zhí)行過程中出現(xiàn)了異常并且自己沒有處理的話才會執(zhí)行通知,throwing是捕獲到的異常用于放在對應method方法中的形參

如果同時配置來所有的通知方式,則執(zhí)行順序依次為:
before>around before>業(yè)務(wù)方法 >after returning > around after > after 或者
before>around before>業(yè)務(wù)方法 >after throwing > after

  • @Before 修飾的方法會在測試之前被執(zhí)行

  • @After 修飾的方法會在測試之后被執(zhí)行 就算有異常也會執(zhí)行

  • AOP的第五種實現(xiàn)方式-xml通知IUserServcie.java

MyAspect.java(切面類)

public class MyAspect {
    //JointPoint(連接點):程序執(zhí)行過程中明確的點,一般是方法的調(diào)用。
    //被攔截到的點,因為Spring只支持方法類型的連接點,
    //所以在Spring中連接點指的就是被攔截到的方法,
    //實際上連接點還可以是字段或者構(gòu)造器
    public void myBefore(JoinPoint jp){
        System.out.println("this is before.");
    }

    public void myAfter(JoinPoint jp){
        System.out.println("this is after.");
    }

    public Object myAround(ProceedingJoinPoint pjp){
        try {
            System.out.println("this is around before");

            Object obj = pjp.proceed();

            System.out.println("this is around after " + obj);

            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        return null;
    }

    /**
     * 帶有返回值的通知
     * @param jp
     * @param obj 配置文件中的obj
     */
    public void myReturn(JoinPoint jp, Object obj){
        System.out.println("this is after returning " + obj);
    }

    public void myThrow(JoinPoint jp, Throwable e){
        System.out.println("this is after throwing " + e.getMessage());
    }
}

beans05.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="us" class="com.qfedu.aop05.UserServiceImpl"/>
    <bean id="ma" class="com.qfedu.aop05.MyAspect" />

    <aop:config proxy-target-class="true">
        <aop:aspect ref="ma">
            <aop:pointcut id="mpc" expression="execution(* com.qfedu.aop05.*.*(..))" />

            <aop:around method="myAround" pointcut-ref="mpc" />
            <aop:before method="myBefore" pointcut-ref="mpc"/>
            <aop:after method="myAfter" pointcut-ref="mpc" />
            <aop:after-returning method="myReturn" pointcut-ref="mpc" returning="obj" />
            <aop:after-throwing method="myThrow" pointcut-ref="mpc" throwing="e" />
        </aop:aspect>
    </aop:config>
</beans>
  • 第六種實現(xiàn)方式--注解式

<?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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--
    context:component-scan 組件掃描
        base-package指定要掃描的包的路徑
    -->
    <context:component-scan base-package="com.qfedu.aop06" />

    <!--aop: aspectj- autoproxy標簽實現(xiàn)自動代理-->
    <aop: aspectj-autoproxy />
</beans>
  • context:component-scan 標簽掃描組件,利用屬性base-package來指定需要掃描組件的位置,xml里還配置了自動代理
    MyAspect.java
package com.qfedu.aop06;

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

/**
 *  以注解的方式實現(xiàn)的切面類MyAspect
 *
 *      當前類中的五種通知方式均以注解方式完成
 */
@Component          //  標注當前類為一個組件
@Aspect             //  標注當前類為一個切面類
public class MyAspect {

    /**
     * @Pointcut 注解為了避免相同的匹配規(guī)則被定義多處,專門定義該方法設(shè)置執(zhí)行的匹配規(guī)則,各個自行調(diào)用即可
     *    write once, only once
     */
    @Pointcut(value = "execution(* com.qfedu.aop06.*.*(..))")
    public void setAll(){}


    /**
     * @Before 表示該方法為一個前置通知
     * @param jp 連接點
     */
    @Before("setAll()")
    public void myBefore(JoinPoint jp){
        //System.out.println(jp.getArgs());
        System.out.println("this is before.");
    }

    /**
     * @After 表示該方法為一個后置通知
     * @param jp 連接點
     */
    @After("setAll()")
    public void myAfter(JoinPoint jp){
        //System.out.println(jp.getArgs());
        System.out.println("this is after.");
    }

    /**
     * @Around 表示該方法為一個環(huán)繞通知
     * @param pjp 處理連接點
     * @return 返回每個業(yè)務(wù)方法的返回值
     */
    @Around("setAll()")
    public Object myAround(ProceedingJoinPoint pjp){
        Object obj = null;
        try {
            System.out.println("this is around before");

            obj = pjp.proceed();


            System.out.println("this is around after");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        return obj;
    }

    /**
     * @AfterReturning 表示該方法為一個帶有返回值的通知
     * @param jp 連接點
     * @param obj 業(yè)務(wù)方法的返回值
     */
    @AfterReturning(value = "setAll()", returning = "obj")
    public void myReturn(JoinPoint jp, Object obj){
        System.out.println("this is after returnning " + obj);
    }

    /**
     * @AfterThrowing 表示該方法為一個帶有異常的通知
     * @param jp 連接點
     * @param e Throwable對象
     */
    @AfterThrowing(value = "setAll()", throwing = "e")
    public void myThrowing(JoinPoint jp, Throwable e){
        System.out.println("this is after throwing " + e.getMessage());
    }
}

在MyAspect類的上方用注解@component標注該類為一個組件,可以被xml里的組件掃描標簽給掃描到,后面的自動代理調(diào)用

  • 第七種實現(xiàn)方式--BeanPostProcessor方法

最后一種使用實現(xiàn)BeanPostProcessor接口類來達到SpringAOP的實現(xiàn),其主要作用是在Bean對象實例化和依賴注入完畢后,再顯示調(diào)用初始化方法的前后添加我們自己的邏輯。注意是在Bean實例化完畢后及依賴注入完成后觸發(fā)的。
2.Bean運行順序:
(1)Spring IoC容器實例化Bean(注意實例化與初始化的區(qū)別,實例化是在內(nèi)存中開辟空間,初始化是對變量賦值)
(2)調(diào)用BeanPostProcesson的postProcessBeforeInitialization方法
(3)調(diào)用Bean實例的初始化方法
(4)調(diào)用BeanPostProcesson的postProcessAfterInitialization方法
具體實現(xiàn)代碼如下所示:
beans07.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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--<bean id="us" class="com.qfedu.aop07.UserServiceImpl" />-->

    <!--
        context:component-scan上下文的組件掃描
            base-package指定要掃描的包為com.qfedu.aop07
    -->
    <context:component-scan base-package="com.qfedu.aop07" />

    <!--
       指定BeanPostProcessor的Factory hook,讓每個bean對象初始化是自動回調(diào)該對象中的回調(diào)方法
    -->
    <bean class="com.qfedu.aop07.MyBeanPostProcessor" />
</beans>

MyBeanPostProcessor.java

package com.qfedu.aop07;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 配置了包掃描之后,該類會初始化兩個對象EventListenerMethodProcessor和DefaultEventListenerFactory,再外加我們自己的組件對象
 *
 * 所以會發(fā)現(xiàn)有三個before打印
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("this is before " + bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("this is after");

        return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                MyAspect ma = new MyAspect();

                ma.before();

                Object obj = method.invoke(bean, args);

                ma.after();

                return obj;
            }
        });
    }
}

實現(xiàn)BeanPostProcessor接口會需要重寫兩個方法分別是 postProcessBeforeInitialization 和 postProcessAfterInitialization,這兩個方法的第一個參數(shù)是目標對象的bean,返回值都是Object類型,因為把bean從IoC容器中取出來還需要放回去,如果返回null的話會報異常.
4.return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() ...)這條語句的作用就是將代理后的對象放進IoC容器中.

  • 常用AOP標簽

1.1<aop:config>

//作用  用于聲明aop的配置
//配置:<aop:config></aop:config>

1.2 <aop:aspect>

/*
作用:
    用于配置切面。
屬性:
    id:給切面提供一個唯一標識。
    ref:引用配置好的通知類bean的id。
配置:<aop:aspect id="logAdvice" ref="logger">
*/

1.3<aop:pointcut>

/*
作用:
    用于配置切入點表達式
屬性:
    expression:用于定義切入點表達式。
    id:用于給切入點表達式提供一個唯一標識。
配置:<aop:pointcut expression="execution(* cn.itcast.service.impl.*.*(..))" id="pt1"/>
*/

1.4<aop:before>

/*
作用:
    用于配置前置通知
屬性:
    method:指定通知中方法的名稱。
    pointct:定義切入點表達式
    pointcut-ref:指定切入點表達式的引用
配置:<aop:before method="beforePrintLog" pointcut-ref="pt1"/>
*/

1.5<aop:after-returning>

/*
作用:
    用于配置后置通知
屬性:
    method:指定通知中方法的名稱。
    pointct:定義切入點表達式
    pointcut-ref:指定切入點表達式的引用
配置:
<aop:after-returning method="afterReturningPrintLog"  pointcut-ref="pt1"/>
*/

1.6<aop:after-throwing>

/*
作用:
    用于配置異常通知
屬性:
    method:指定通知中方法的名稱。
    pointct:定義切入點表達式
    pointcut-ref:指定切入點表達式的引用
配置:<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/>
*/

1.7 <aop:after>

/*
作用:
    用于配置最終通知
屬性:
    method:指定通知中方法的名稱。
    pointct:定義切入點表達式
    pointcut-ref:指定切入點表達式的引用
配置:<aop:after method="afterPrintLog" pointcut-ref="pt1"/>
*/

1.8<aop:around>

/*
作用:
        用于配置環(huán)繞通知
    屬性:
        method:指定通知中方法的名稱。
        pointct:定義切入點表達式
        pointcut-ref:指定切入點表達式的引用
    配置:<aop:around method="transactionAround" pointcut-ref="pt1"/>
說明:
        它是spring框架為我們提供的一種可以在代碼中手動控制增強代碼什么時候執(zhí)行的方式。
    注意:
        通常情況下,環(huán)繞通知都是獨立使用的
*/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 靈修、心理、心靈跟靈魂很近了,《找到你的靈魂伴侶》看到這本書的時候,感覺自己就是那種要找的靈魂上能夠交融的靈魂伴侶...
    平步天閱讀 247評論 0 0
  • 印度南部- Chennai,Tamil Nadu(二) 金奈,我們印度之旅的最后一程。 教堂,印度廟,博物館,這是...
    楊婠婠閱讀 865評論 0 1
  • 山神|目錄 山神|上一章 “老爺英明,是子戒不錯?!蹦凶庸Ь吹氐皖^拱手,“老爺醒得這般早,果然早就修煉得道,若不是...
    杏垣閱讀 530評論 10 9
  • 每個人一生都會遇見不同的人,會有不同的境遇。生命是有延續(xù)的,正如花開花落,植株死了,但種子會有新的生命。但是如果植...
    貢獻干凈閱讀 330評論 0 0
  • 看著比賽的數(shù)據(jù): 勝利的時候,基本上都是隊友很給力,或者說對手很垃圾。 失敗的時候,基本上都是隊友很垃圾,或者說對...
    劍心折手閱讀 334評論 0 0

友情鏈接更多精彩內(nèi)容