Spring Boot使用AOP實現攔截某個方法

2022-07-03 10:15:13 字數 2039 閱讀 7493

1、引入.jarl檔案依賴

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-tomcat

2、引入aop相關的jar

org.springframework.boot

spring-boot-starter-aop

3、編寫interceptor攔截類,兩種方式實現

@aspect

@component

public

class

callbackloginterceptor

protected

void

committx(transactionstatus transactionstatus)

}protected

void

rollbacktx(transactionstatus transactionstatus)

}@afterreturning(pointcut = "execution(* com.gcard.notify.sevice.impl.notifycashmanager.notifycash(..))&&args(notifyurl, cashid, reqsn, callresult)", returning = "resultvalue")

public

void

handleinsertcallbacklog(string resultvalue,string notifyurl, string cashid, string reqsn, string callresult)

catch

(exception e)

}@afterthrowing(pointcut = "execution(* com.gcard.notify.sevice.impl.notifycashmanager.notifycash(..))&&args(notifyurl, cashid, reqsn, callresult)", throwing="ex")

public

void

handleupdatecashafterthrow(throwable ex,string notifyurl, string cashid, string reqsn, string callresult)

catch

(exception e)

}}

public

void

adddo()

@afterreturning(pointcut = "adddo()", returning = "resultvalue")

public

void

adddopayafterreturning(joinpoint jp, object resultvalue)

}else

if(resultvalue instanceof

returnresult)

}else

}} catch

(exception e)

}注意:攔截的方法要是乙個bean呼叫才能生效,比如:攔截的notifycash()方法,需要獨立在乙個類,然後被其他類呼叫

@component

public

class

notifycashmanager

else

}return

msg;}}

}

被呼叫:

@autowired

private

notifycashmanager notifycashmanager;

notifycashmanager.notifycash(notifyurl, cashid, reqsn, callresult);//呼叫方式

Springboot如何使用AOP

切面的包 1 springboot 不自帶aop 需要自己新增依賴 org.springframework.bootgroupid spring boot starter aopartifactid dependency 2 直接 aspect寫切面類就行了1 連線點 可以理解為需要被增強的方法 2...

Spring Boot 之優雅使用 AOP

aop為aspect oriented programming的縮寫,意思是面向切面程式設計,通過預編譯的方式和執行時動態 實現程式功能的統一維護的一種技術。利用aop可以對業務邏輯進行分離,降低耦合度,提高可重用性,提高開發效率。主要用途 日誌記錄 事務處理 異常處理 安全處理 效能統計 在spr...

Springboot 中AOP的使用

面向切面程式設計 aspect oriented programming 是軟體程式設計思想發展到一定階段的產物,是物件導向程式設計的有益補充。aop一般適用於具有橫切邏輯的場合,如訪問控制 事務管理 效能檢測等。日誌 異常處理 事務控制等都是乙個健壯的業務系統所必須的。但是為了保證系統健壯可用,就...