springAOP的三種實(shí)現(xiàn)方式分別是什么

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)springAOP的三種實(shí)現(xiàn)方式分別是什么,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)新互聯(lián)公司是一家專業(yè)提供威縣企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站制作、成都網(wǎng)站建設(shè)H5頁(yè)面制作、小程序制作等業(yè)務(wù)。10年已為威縣眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。

springAOP的實(shí)現(xiàn)方式

三種
純XML方式,XML+注解,純注解方式。

Spring 實(shí)現(xiàn)AOP思想使?的是動(dòng)態(tài)代理技術(shù)
默認(rèn)情況下, Spring會(huì)根據(jù)被代理對(duì)象是否實(shí)現(xiàn)接?來(lái)選擇使?JDK還是CGLIB。當(dāng)被代理對(duì)象沒(méi)有實(shí)現(xiàn)

任何接?時(shí), Spring會(huì)選擇CGLIB。當(dāng)被代理對(duì)象實(shí)現(xiàn)了接?, Spring會(huì)選擇JDK官?的代理技術(shù),不過(guò)

我們可以通過(guò)配置的?式,讓Spring強(qiáng)制使?CGLIB。

接下來(lái)我們開(kāi)始實(shí)現(xiàn)aop,
需求是:橫切邏輯代碼是打印?志,希望把打印?志的邏輯織?到?標(biāo)?法的特定位置(service層transfer?法)

純XML方式

引入aop相關(guān)的jar包

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>5.1.12.RELEASE</version></dependency><dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version></dependency>

TransferServiceImpl.java文件:

package com.lagou.edu.service.impl;import com.lagou.edu.dao.AccountDao;import com.lagou.edu.pojo.Account;import com.lagou.edu.service.TransferService;import com.lagou.edu.utils.ConnectionUtils;import com.lagou.edu.utils.TransactionManager;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.ImportResource;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;/**
 * @author 應(yīng)癲
 */@Service("transferService")public class TransferServiceImpl implements TransferService {    // 最佳狀態(tài)
    // @Autowired 按照類型注入 ,如果按照類型無(wú)法唯一鎖定對(duì)象,可以結(jié)合@Qualifier指定具體的id
    @Autowired
    @Qualifier("accountDao")    private AccountDao accountDao;    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {        /*try{
            // 開(kāi)啟事務(wù)(關(guān)閉事務(wù)的自動(dòng)提交)
            TransactionManager.getInstance().beginTransaction();*/
            System.out.println("執(zhí)行轉(zhuǎn)賬業(yè)務(wù)邏輯");
            Account from = accountDao.queryAccountByCardNo(fromCardNo);
            Account to = accountDao.queryAccountByCardNo(toCardNo);
            from.setMoney(from.getMoney()-money);
            to.setMoney(to.getMoney()+money);
            accountDao.updateAccountByCardNo(to);            //int c = 1/0;
            accountDao.updateAccountByCardNo(from);
    }
}

打印日志Util:

package com.lagou.edu.utils;/**
 * @author 應(yīng)癲
 */public class LogUtils {    /**
     * 業(yè)務(wù)邏輯開(kāi)始之前執(zhí)行
     */
    
    public void beforeMethod(JoinPoint joinPoint) {
          Object[] args = joinPoint.getArgs();        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            System.out.println(arg);
        }
        System.out.println("業(yè)務(wù)邏輯開(kāi)始執(zhí)行之前執(zhí)行.......");
    }    /**
     * 業(yè)務(wù)邏輯結(jié)束時(shí)執(zhí)行(無(wú)論異常與否)
     */
    public void afterMethod() {
        System.out.println("業(yè)務(wù)邏輯結(jié)束時(shí)執(zhí)行,無(wú)論異常與否都執(zhí)行.......");
    }    /**
     * 異常時(shí)時(shí)執(zhí)行
     */
    public void exceptionMethod() {
        System.out.println("異常時(shí)執(zhí)行.......");
    }    /**
     * 業(yè)務(wù)邏輯正常時(shí)執(zhí)行
     */
    public void successMethod(Object retVal) {
        System.out.println("業(yè)務(wù)邏輯正常時(shí)執(zhí)行.......");
    }
}public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("環(huán)繞通知中的beforemethod....");
        Object result = null;        try{            // 控制原有業(yè)務(wù)邏輯是否執(zhí)行
            // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        }catch(Exception e) {
            System.out.println("環(huán)繞通知中的exceptionmethod....");
        }finally {
            System.out.println("環(huán)繞通知中的after method....");
        }        return result;
    }

applicationContext.xml

<!--進(jìn)行aop相關(guān)的xml配置,配置aop的過(guò)程其實(shí)就是把a(bǔ)op相關(guān)術(shù)語(yǔ)落地-->
    <!--橫切邏輯bean--><bean id="logUtils" class="com.lagou.edu.utils.LogUtils"></bean>
   <!--使用config標(biāo)簽表明開(kāi)始aop配置,在內(nèi)部配置切面aspect-->
   <!--aspect   =    切入點(diǎn)(鎖定方法) + 方位點(diǎn)(鎖定方法中的特殊時(shí)機(jī))+ 橫切邏輯 -->
    <aop:config>
        <aop:aspect id="logAspect" ref="logUtils">
           <!--切入點(diǎn)鎖定我們感興趣的方法,使用aspectj語(yǔ)法表達(dá)式-->
           <!--..參數(shù)中的兩個(gè)點(diǎn)表示可以有參數(shù),也可以沒(méi)有參數(shù),有的話也可以是任意類型,參數(shù)中的 *表示參數(shù)可以是任意類型,但必須有參數(shù)。 -->
           <!--包名中的..兩個(gè)點(diǎn)表示中間可以是任意層-->
           <!--<aop:pointcut id="pt1" expression="execution(* *..*.*(..))"/>-->
         <aop:pointcut id="pt1" expression="execution(public void com.lagou.edu.service.impl.TransferServiceImpl.transfer(java.lang.String,java.lang.String,int))"/><!--           <aop:pointcut id="pt1" expression="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/>
-->
           <!--方位信息,pointcut-ref關(guān)聯(lián)切入點(diǎn)-->
           <!--aop:before前置通知/增強(qiáng)-->
            <aop:before method="beforeMethod" pointcut-ref="pt1"/>
           <!--aop:after,最終通知,無(wú)論如何都執(zhí)行-->
           <!--aop:after-returnning,正常執(zhí)行通知,retValue是接受方法的返回值的-->
            <aop:after-returning method="successMethod" returning="retValue"/>
           <!--aop:after-throwing,異常通知-->
            <aop:around method="arroundMethod" pointcut-ref="pt1"/>
        </aop:aspect>
    </aop:config>-->

測(cè)試:

    /**
     * 測(cè)試xml aop
     */
    @Test
    public void testXmlAop() throws Exception {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        TransferService transferService = applicationContext.getBean(TransferService.class);
        transferService.transfer("6029621011000","6029621011001",100);
    }

環(huán)繞通知不和前置及后置通知一起使用,因?yàn)榄h(huán)繞通知可以實(shí)現(xiàn)前置和后置的功能,并且可以控制原有業(yè)務(wù)邏輯是否執(zhí)行,非常強(qiáng)大。

XML+注解方式

將上面純XML方式改為注解方式
將applicationContext.xml中的內(nèi)容取掉,改為類中添加注解:

package com.lagou.edu.utils;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;/**
 * @author 應(yīng)癲
 */@Component@Aspectpublic class LogUtils {    @Pointcut("execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))")    public void pt1(){
    }    /**
     * 業(yè)務(wù)邏輯開(kāi)始之前執(zhí)行
     */
    @Before("pt1()")    public void beforeMethod(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            System.out.println(arg);
        }
        System.out.println("業(yè)務(wù)邏輯開(kāi)始執(zhí)行之前執(zhí)行.......");
    }    /**
     * 業(yè)務(wù)邏輯結(jié)束時(shí)執(zhí)行(無(wú)論異常與否)
     */
    @After("pt1()")    public void afterMethod() {
        System.out.println("業(yè)務(wù)邏輯結(jié)束時(shí)執(zhí)行,無(wú)論異常與否都執(zhí)行.......");
    }    /**
     * 異常時(shí)時(shí)執(zhí)行
     */
    @AfterThrowing("pt1()")    public void exceptionMethod() {
        System.out.println("異常時(shí)執(zhí)行.......");
    }    /**
     * 業(yè)務(wù)邏輯正常時(shí)執(zhí)行
     */
    @AfterReturning(value = "pt1()",returning = "retVal")    public void successMethod(Object retVal) {
        System.out.println("業(yè)務(wù)邏輯正常時(shí)執(zhí)行.......");
    }    /**
     * 環(huán)繞通知
     *
     */
    /*@Around("pt1()")*/
    public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("環(huán)繞通知中的beforemethod....");
        Object result = null;        try{            // 控制原有業(yè)務(wù)邏輯是否執(zhí)行
            // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        }catch(Exception e) {
            System.out.println("環(huán)繞通知中的exceptionmethod....");
        }finally {
            System.out.println("環(huán)繞通知中的after method....");
        }        return result;
    }
}

在application.xml中配置注解驅(qū)動(dòng):

    <!--開(kāi)啟aop注解驅(qū)動(dòng)
        proxy-target-class:true強(qiáng)制使用cglib
    -->
    <aop:aspectj-autoproxy/>

純注解模式

我們只需要替換掉xml+注解模式中的注解驅(qū)動(dòng)的部分即可,

    <!--開(kāi)啟aop注解驅(qū)動(dòng)
        proxy-target-class:true強(qiáng)制使用cglib
    -->
    <aop:aspectj-autoproxy/>

改為 @EnableAspectJAutoProxy //開(kāi)啟spring對(duì)注解AOP的?持,在項(xiàng)目中添加到任意個(gè)配置類上即可。

上述就是小編為大家分享的springAOP的三種實(shí)現(xiàn)方式分別是什么了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

新聞名稱:springAOP的三種實(shí)現(xiàn)方式分別是什么
文章URL:http://muchs.cn/article18/ippsdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)商城網(wǎng)站、建站公司、網(wǎng)站維護(hù)動(dòng)態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營(yíng)