spring AOP切面,註解實現,獲取參數

Spring的AOP有兩種實現方式,一是通過xml配置,二是通過註解,爲減少代碼量提高可讀性跟代碼入侵本,若項目使用了spring的框架,本人首選的都是用註解去開發,方法很簡單,只需要三步就可以搞定切面


一:在xml文件中開始註解

<!--AOP切面,將所有被Aspectj標註的類生成所有代理對象-->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

二:定義切面類,加上註解

/**
 * 用戶操作記錄日誌 切面控制層
 * Created by longzhiqinag on 2017/3/29.
 */
@Aspect
@Component
public class UserOperateLogHandler{

}



三:在切面類上指定要進行AOP切面的方法

    @Before("execution(* com.tangcy.npcmeeting.controller.MeetingController.deleteBigMeeting(..))")
    public void deleteBigMeeting_Before(JoinPoint joinPoint){
        System.out.println("這裏是目標方法執行前先執行");
    }
    @AfterReturning(returning = "entity",value = "execution(* com.tangcy.npcmeeting.controller.MeetingController.deleteBigMeeting(..))")
    public void deleteBigMeeting_After(JoinPoint joinPoint,Object entity){
        System.out.println("這裏是目標方法執行完併成功返回結果 正常結束後才執行");
        System.out.println("方法的返回結果爲"+entity);
        System.out.println("目標方法內的參數爲"+ Arrays.asList(joinPoint.getArgs()));
    }
    @AfterThrowing(throwing = "e",value = "execution(* com.tangcy.npcmeeting.controller.MeetingController.deleteBigMeeting(..))")
    public void deleteBigMeeting_Throw(Throwable  e){
        System.out.println("這裏是目標方法拋出異常後才執行");
        System.out.println("異常信息爲"+e);
    }



用大白話說
  1. 由@Before註解定義的方法會在 execution() 表達式內的方法被調用之前執行
  2. 由@After註解定義的方法會在 execution()表達式內的方法被調用之後執行,無論方法執行成功與否
  3. 由@AfterReturning註解定義的方法會在 execution()表達式內的方法被調用之後併成功返回結果後執行,若拋出異常AfterReturning不會執行
  4. 由@AfterThrowing註解定義的方法會在 execution()表達式內的方法拋出異常後執行
  5. 由@Around註解定義的方法包裹了被通知的方法,在被通知的方法調用之前和調用之後執行自定義的行爲
execution表達式
如:@AfterReturning("execution(* com.tangcy.npcmeeting.controller.OperateController.save(..))")
* 代表匹配方法的所有修飾符和所有返回值,經測式,方法修飾符若爲private則不行,會出錯 500,這裏也可以這樣寫
@AfterReturning("execution(public void com.tangcy.npcmeeting.controller.OperateController.save(..))")
在 * 的位置換成你的方法修飾符跟返回值類型即可
.. 代表匹配方法的所有參數,無論該方法有多少個參數,是什麼類型都匹配,若你的方法行參類型爲String 也可以這樣寫
在..的地方換成你的參數類型即可,可寫多個參數類型
@AfterReturning("execution(* com.tangcy.npcmeeting.controller.OperateController.save(String))")
com.tangcy.npcmeeting.controller 爲方法的包路徑/名

在你自定義的方法上加上 JoinPoint做爲參數 可以獲取將被切面方法的參數 注意是 
org.aspectj.lang.JoinPoint;這個包下的JoinPoint,返回值類型爲Object[],需自已轉換類型
如以下爲自定義的方法 
@AfterReturning("execution(public void com.tangcy.npcmeeting.controller.OperateController.save(..))")
public void save_After(JoinPoint joinPoint){
	Object[] obj = joinPoint.getArgs();
	//將obj強轉爲你的參數類型再進行對應的操作
}
所有的註解通知用法都一樣,這裏只是用@AfterReturning來舉例說明
很簡單吧...


發佈了43 篇原創文章 · 獲贊 36 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章