之前學習Spring的時候着重學習過AOP概念,可是一直也沒有用上,惟一碰到過的就是Spring內置的事務管理。如今碰到過一些結果後面的操做適合用到,因此這裏就拿出來用一下,而且複習一下落下的知識。node
基本概念這個博主解釋的比較清楚,若是有不懂的能夠去看一下。https://blog.csdn.net/csh624366188/article/details/7651702web
在個人認識裏,若是某些方法重複性特別高,能夠抽象出來造成一個切面,則可使用AOP來簡化代碼,即在方法的某些部分動態的添加某些方法,起到簡化代碼的做用。spring
項目的Service層經過webService獲取到數據,須要對獲取到的數據進行判斷處理,對其異常信息做出記錄和拋出異常。同時還須要在進入和結束方法的時候進行日誌記錄。json
配置方法:app
在這裏使用的是註解的方式來配置的AOP,首先,要保證項目中除了Spring基本包之外還包含aopalliance-1.0.jar,aspectjrt-1.8.7.jar,aspectjweaver-1.8.7.jar,cglib-nodep-3.2.4.jar這四個jar包,這裏將其打包放到百度雲,若是有須要的能夠去下載。連接:https://pan.baidu.com/s/1rDqLY1lnWdiahVkLcZd_bw 密碼:0uea學習
Spring配置添加以下, 添加<aop:aspectj-autoproxy />須要添加Spring的頭部內容測試
注意aop不能添加到static方法上面。spa
<aop:aspectj-autoproxy /> // 掃描AOP <!-- 這裏配置後就不用再使用bean標籤配置bean了 --> <context:annotation-config></context:annotation-config> <!-- 去哪一個包掃描生成bean --> <context:component-scan base-package="com.dazhong.jnfy.alipay.action" />
首選創建切面類:其中的afterReturning就是主要的切面方法,用於對返回值進行判斷而且進行對應的操做,這樣能夠不用再每一個方法中都寫一次。.net
@Pointcut("execution(* com.dazhong.jnfy.alipay.service.impl.*.*(..))"):表示AOP會代理那些方法,這裏則表示com.dazhong.jnfy.alipay.service.impl包下面全部方法都會執行
@After("picter()"):後置通知
@Before("picter()"):前置通知
package com.dazhong.jnfy.alipay.aop;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.json.JSONObject; import org.springframework.stereotype.Component; import com.dazhong.jnfy.alipay.exception.ConnectionException; import com.dazhong.jnfy.alipay.exception.ResultErrorException; import com.dazhong.utils.LogUtil; @Component @Aspect public class ServiceAop { @Pointcut("execution(* com.dazhong.jnfy.alipay.service.impl.*.*(..))") public void picter() { } /** * @Description: 對返回值進行處理 * @param point * @param rvt * @throws ResultErrorException */ @AfterReturning(returning = "rvt", pointcut = "execution(* com.dazhong.jnfy.alipay.service.impl.*.*(..))") public void afterReturning(JoinPoint point, Object rvt) throws Exception { // Object rvt則是方法返回值,這裏變量名稱要和註解retruning值相同 String[] strs = point.getSignature().getDeclaringTypeName().split("\\."); String fullname = strs[strs.length - 1] + "." + point.getSignature().getName(); JSONObject root = (JSONObject) rvt; if (rvt == null) { throw new ConnectionException("WebService鏈接失敗" + fullname); } else if (!root.has("resultCode") || !root.get("resultCode").toString().equals("0")) { // 返回數據異常 throw new ResultErrorException("WebService 返回結果異常:" + root.toString()); } } @Before("picter()") public void before(JoinPoint point) { String[] strs = point.getSignature().getDeclaringTypeName().split("\\."); String fullname = strs[strs.length - 1] + "." + point.getSignature().getName(); LogUtil.info("進入方法:" + fullname); } @After("picter()") public void after(JoinPoint point) { String[] strs = point.getSignature().getDeclaringTypeName().split("\\."); String fullname = strs[strs.length - 1] + "." + point.getSignature().getName(); LogUtil.info("方法結束:" + fullname); } }
獲取參數/方法名:代理
若是須要獲取目標方法的參數/名字,則須要在切面的方法中添加變量 JoinPoint point,經過這個對象來進行獲取。
String allname = point.getSignature().getDeclaringTypeName(); // 獲取整個路徑 包名+類名
System.out.println(allname);
String[] split = allname.split("\\."); System.out.println("目標方法:" + split[split.length - 1] + "." + point.getSignature().getName()); // point.getSignature().getName() 獲取方法名 System.out.println("@Before:參數爲:" + Arrays.toString(point.getArgs())); // 獲取目標方法的參數 point.getArgs()
結果: 紅框內容就是AOP自動添加的。
剩餘代碼:
目標方法:
public JSONObject test() throws Exception{
System.out.println("目標方法執行"); JSONObject js = new JSONObject(); js.put("resultCode", "-1"); return js; }
測試方法:
public static void main(String[] args) {
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml"); ReserveServiceImpl b = (ReserveServiceImpl) appCtx.getBean("reserveServiceImpl"); JSONObject js = new JSONObject(); js.put("s", "111"); try { //JSONObject allDept = b.getDocterByTimeAndDept("YYKS002", "20180711"); b.test(); } catch (Exception e) { System.out.println(e); } }