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{
}
@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);
}
用大白話說
- 由@Before註解定義的方法會在 execution() 表達式內的方法被調用之前執行
- 由@After註解定義的方法會在 execution()表達式內的方法被調用之後執行,無論方法執行成功與否
- 由@AfterReturning註解定義的方法會在 execution()表達式內的方法被調用之後併成功返回結果後執行,若拋出異常AfterReturning不會執行
- 由@AfterThrowing註解定義的方法會在 execution()表達式內的方法拋出異常後執行
- 由@Around註解定義的方法包裹了被通知的方法,在被通知的方法調用之前和調用之後執行自定義的行爲
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來舉例說明
很簡單吧...