1. 程式人生 > 程式設計 >springAOP的三種實現方式示例程式碼

springAOP的三種實現方式示例程式碼

這篇文章給大家介紹了springAOP的實現方式,三種分別是純XML方式,XML+註解,純註解方式。

Spring 實現AOP思想使⽤的是動態代理技術
預設情況下, Spring會根據被代理物件是否實現接⼝來選擇使⽤JDK還是CGLIB。當被代理物件沒有實現

任何接⼝時, Spring會選擇CGLIB。當被代理物件實現了接⼝, Spring會選擇JDK官⽅的代理技術,不過

我們可以通過配置的⽅式,讓Spring強制使⽤CGLIB。

接下來我們開始實現aop,
需求是:橫切邏輯程式碼是列印⽇志,希望把列印⽇志的邏輯織⼊到⽬標⽅法的特定位置(service層transfer⽅法)

純XML方式

引入aop相關的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 應癲
 */
@Service("transferService")
public class TransferServiceImpl implements TransferService {
  // 最佳狀態
  // @Autowired 按照型別注入,如果按照型別無法唯一鎖定物件,可以結合@Qualifier指定具體的id
  @Autowired
  @Qualifier("accountDao")
  private AccountDao accountDao;

  @Override
  public void transfer(String fromCardNo,String toCardNo,int money) throws Exception {
    /*try{
      // 開啟事務(關閉事務的自動提交)
      TransactionManager.getInstance().beginTransaction();*/
      System.out.println("執行轉賬業務邏輯");
      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 應癲
 */

public class LogUtils {

  /**
   * 業務邏輯開始之前執行
   */
  
  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("業務邏輯開始執行之前執行.......");
  }


  /**
   * 業務邏輯結束時執行(無論異常與否)
   */

  public void afterMethod() {
    System.out.println("業務邏輯結束時執行,無論異常與否都執行.......");
  }

  /**
   * 異常時時執行
   */
  public void exceptionMethod() {
    System.out.println("異常時執行.......");
  }

  /**
   * 業務邏輯正常時執行
   */

  public void successMethod(Object retVal) {
    System.out.println("業務邏輯正常時執行.......");
  }

}

public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("環繞通知中的beforemethod....");

    Object result = null;
    try{
      // 控制原有業務邏輯是否執行
      // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }catch(Exception e) {
      System.out.println("環繞通知中的exceptionmethod....");
    }finally {
      System.out.println("環繞通知中的after method....");
    }

    return result;
  }

applicationContext.xml

<!--進行aop相關的xml配置,配置aop的過程其實就是把aop相關術語落地-->
  <!--橫切邏輯bean-->
<bean id="logUtils" class="com.lagou.edu.utils.LogUtils"></bean>
  <!--使用config標籤表明開始aop配置,在內部配置切面aspect-->

  <!--aspect  =  切入點(鎖定方法) + 方位點(鎖定方法中的特殊時機)+ 橫切邏輯 -->
  <aop:config>
    <aop:aspect id="logAspect" ref="logUtils">

      <!--切入點鎖定我們感興趣的方法,使用aspectj語法表示式-->
      <!--..引數中的兩個點表示可以有引數,也可以沒有引數,有的話也可以是任意型別,引數中的 *表示引數可以是任意型別,但必須有引數。 -->
      <!--包名中的..兩個點表示中間可以是任意層-->
      <!--<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關聯切入點-->
      <!--aop:before前置通知/增強-->
      <aop:before method="beforeMethod" pointcut-ref="pt1"/>
      <!--aop:after,最終通知,無論如何都執行-->
      <!--aop:after-returnning,正常執行通知,retValue是接受方法的返回值的-->
      <aop:after-returning method="successMethod" returning="retValue"/>
      <!--aop:after-throwing,異常通知-->

      <aop:around method="arroundMethod" pointcut-ref="pt1"/>

    </aop:aspect>
  </aop:config>-->

測試:

 /**
   * 測試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);
  }

環繞通知不和前置及後置通知一起使用,因為環繞通知可以實現前置和後置的功能,並且可以控制原有業務邏輯是否執行,非常強大。

XML+註解方式

將上面純XML方式改為註解方式
將applicationContext.xml中的內容取掉,改為類中添加註解:

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 應癲
 */
@Component
@Aspect
public class LogUtils {


  @Pointcut("execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))")
  public void pt1(){

  }


  /**
   * 業務邏輯開始之前執行
   */
  @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("業務邏輯開始執行之前執行.......");
  }


  /**
   * 業務邏輯結束時執行(無論異常與否)
   */
  @After("pt1()")
  public void afterMethod() {
    System.out.println("業務邏輯結束時執行,無論異常與否都執行.......");
  }


  /**
   * 異常時時執行
   */
  @AfterThrowing("pt1()")
  public void exceptionMethod() {
    System.out.println("異常時執行.......");
  }


  /**
   * 業務邏輯正常時執行
   */
  @AfterReturning(value = "pt1()",returning = "retVal")
  public void successMethod(Object retVal) {
    System.out.println("業務邏輯正常時執行.......");
  }


  /**
   * 環繞通知
   *
   */
  /*@Around("pt1()")*/
  public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("環繞通知中的beforemethod....");

    Object result = null;
    try{
      // 控制原有業務邏輯是否執行
      // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }catch(Exception e) {
      System.out.println("環繞通知中的exceptionmethod....");
    }finally {
      System.out.println("環繞通知中的after method....");
    }

    return result;
  }

}

在application.xml中配置註解驅動:

 <!--開啟aop註解驅動
    proxy-target-class:true強制使用cglib

  -->
  <aop:aspectj-autoproxy/>

純註解模式

我們只需要替換掉xml+註解模式中的註解驅動的部分即可,

 <!--開啟aop註解驅動
    proxy-target-class:true強制使用cglib

  -->
  <aop:aspectj-autoproxy/>

改為 @EnableAspectJAutoProxy //開啟spring對註解AOP的⽀持,在專案中新增到任意個配置類上即可。

到此這篇關於springAOP的三種實現方式的文章就介紹到這了,更多相關springAOP實現方式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!