1. 程式人生 > >SpringCloud開發學習總結(六)—— 結合註解的AOP示例

SpringCloud開發學習總結(六)—— 結合註解的AOP示例

分析 urn 需要 開發 tostring ole ngs artifact tex

  面向切面編程,通過預編譯方式和運行期動態代理實現程序功能的統一維護的一種技術。AOP是OOP的延續,是軟件開發中的一個熱點,也是Spring框架中的一個重要內容,是函數式編程的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程序的可重用性,同時提高了開發的效率。

  我們現在做的一些非業務,如:日誌、事務、安全等都會寫在業務代碼中(也即是說,這些非業務類橫切於業務類),但這些代碼往往是重復,復制——粘貼式的代碼會給程序的維護帶來不便,AOP就實現了把這些業務需求與系統需求分開來做。這種解決的方式也稱代理機制。

技術分享圖片技術分享圖片

先來了解一下AOP的相關概念,《Spring參考手冊》中定義了以下幾個AOP的重要概念,結合下面示例分析如下:

  1. 切面(Aspect):官方的抽象定義為“一個關註點的模塊化,這個關註點可能會橫切多個對象”,在本例中,“切面”就是類TestAspect所關註的具體行為,例如,AServiceImpl.barA()的調用就是切面TestAspect所關註的行為之一。“切面”在ApplicationContext中<aop:aspect>來配置。
  • 連接點(Joinpoint) :程序執行過程中的某一行為,例如,UserService.get的調用或者UserService.delete拋出異常等行為。
  • 通知(Advice) :“切面”對於某個“連接點”所產生的動作,例如,TestAspect中對com.spring.service包下所有類的方法進行日誌記錄的動作就是一個Advice。其中,一個“切面”可以包含多個“Advice”,例如ServiceAspect。
  • 切入點(Pointcut) :匹配連接點的斷言,在AOP中通知和一個切入點表達式關聯。例如,TestAspect中的所有通知所關註的連接點,都由切入點表達式execution(* com.spring.service.*.*(..))來決定。
  • 目標對象(Target Object) :被一個或者多個切面所通知的對象。例如,AServcieImpl和BServiceImpl,當然在實際運行時,Spring AOP采用代理實現,實際AOP操作的是TargetObject的代理對象。
  • AOP代理(AOP Proxy) :在Spring AOP中有兩種代理方式,JDK動態代理和CGLIB代理。默認情況下,TargetObject實現了接口時,則采用JDK動態代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。強制使用CGLIB代理需要將 <aop:config>的 proxy-target-class屬性設為true。

通知(Advice)類型:

  • 前置通知(Before advice):在某連接點(JoinPoint)之前執行的通知,但這個通知不能阻止連接點前的執行。ApplicationContext中在<aop:aspect>裏面使用<aop:before>元素進行聲明。例如,TestAspect中的doBefore方法。
  • 後置通知(After advice):當某連接點退出的時候執行的通知(不論是正常返回還是異常退出)。ApplicationContext中在<aop:aspect>裏面使用<aop:after>元素進行聲明。例如,ServiceAspect中的returnAfter方法,所以Teser中調用UserService.delete拋出異常時,returnAfter方法仍然執行。
  • 返回後通知(After return advice):在某連接點正常完成後執行的通知,不包括拋出異常的情況。ApplicationContext中在<aop:aspect>裏面使用<after-returning>元素進行聲明。
  • 環繞通知(Around advice):包圍一個連接點的通知,類似Web中Servlet規範中的Filter的doFilter方法。可以在方法的調用前後完成自定義的行為,也可以選擇不執行。ApplicationContext中在<aop:aspect>裏面使用<aop:around>元素進行聲明。例如,ServiceAspect中的around方法。
  • 拋出異常後通知(After throwing advice):在方法拋出異常退出時執行的通知。ApplicationContext中在<aop:aspect>裏面使用<aop:after-throwing>元素進行聲明。例如,ServiceAspect中的returnThrow方法。

接下來通過一下例子來演示SpringCloud+aop

  • 在pom.xml文件中引入(starter中默認添加了@EnableAspectJAutoProxy)

1 <!--引用AOP註解功能開始--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-aop</artifactId> 5 </dependency> 6 <!--引用AOP註解功能結束-->

  • 自定義一個註解,用於註解式AOP
public enum LogType {
    INFO, WARN, ERROR
}
 1 /**
 2  * 系統日誌記錄
 3  * 
 4  * @author cjg
 5  *
 6  */
 7 @Target({ ElementType.METHOD })
 8 @Retention(RetentionPolicy.RUNTIME)
 9 @Documented
10 public @interface ServiceLog {
11     /**
12      * 操作類型,新增用戶?刪除用戶 ?調用xx服務?使用接口?...
13      * 
14      * @return
15      */
16     public String operation();
17 
18     /**
19      * 日誌級別
20      * 
21      * @return
22      */
23     public LogType level() default LogType.INFO;
24 
25 }
  • 使用@Aspect註解將一個java類定義為切面類
  1 @Component
  2 @Aspect
  3 public class LogAspect {
  4 
  5     private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
  6 
  7     /**
  8      * 切入點
  9      */
 10     @Pointcut("@annotation(com.didispace.web.aspect.ServiceLog) ")
 11     public void entryPoint() {
 12         // 無需內容
 13     }
 14 
 15     @Before("entryPoint()")
 16     public void before(JoinPoint joinPoint) {
 17 
 18         log.info("=====================開始執行前置通知==================");
 19         try {
 20             String targetName = joinPoint.getTarget().getClass().getName();
 21             String methodName = joinPoint.getSignature().getName();
 22             Object[] arguments = joinPoint.getArgs();
 23             Class<?> targetClass = Class.forName(targetName);
 24             Method[] methods = targetClass.getMethods();
 25             String operation = "";
 26             for (Method method : methods) {
 27                 if (method.getName().equals(methodName)) {
 28                     Class<?>[] clazzs = method.getParameterTypes();
 29                     if (clazzs.length == arguments.length) {
 30                         operation = method.getAnnotation(ServiceLog.class).operation();// 操作人
 31                         break;
 32                     }
 33                 }
 34             }
 35             StringBuilder paramsBuf = new StringBuilder();
 36             for (Object arg : arguments) {
 37                 paramsBuf.append(arg);
 38                 paramsBuf.append("&");
 39             }
 40 
 41             // *========控制臺輸出=========*//
 42             log.info("[X用戶]執行了[" + operation + "],類:" + targetName + ",方法名:" + methodName + ",參數:"
 43                     + paramsBuf.toString());
 44             log.info("=====================執行前置通知結束==================");
 45         } catch (Throwable e) {
 46             log.info("around " + joinPoint + " with exception : " + e.getMessage());
 47         }
 48 
 49     }
 50 
 51     /**
 52      * 環繞通知處理處理
 53      * 
 54      * @param joinPoint
 55      * @throws Throwable
 56      */
 57     @Around("entryPoint()")
 58     public Object around(ProceedingJoinPoint point) throws Throwable {
 59         // 先執行業務,註意:業務這樣寫業務發生異常不會攔截日誌。
 60         Object result = point.proceed();
 61         try {
 62             handleAround(point);// 處理日誌
 63         } catch (Exception e) {
 64             log.error("日誌記錄異常", e);
 65         }
 66         return result;
 67     }
 68 
 69     /**
 70      * around日誌記錄
 71      * 
 72      * @param point
 73      * @throws SecurityException
 74      * @throws NoSuchMethodException
 75      */
 76     public void handleAround(ProceedingJoinPoint point) throws Exception {
 77         Signature sig = point.getSignature();
 78         MethodSignature msig = null;
 79         if (!(sig instanceof MethodSignature)) {
 80             throw new IllegalArgumentException("該註解只能用於方法");
 81         }
 82         msig = (MethodSignature) sig;
 83         Object target = point.getTarget();
 84         Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
 85         // 方法名稱
 86         String methodName = currentMethod.getName();
 87         // 獲取註解對象
 88         ServiceLog aLog = currentMethod.getAnnotation(ServiceLog.class);
 89         // 類名
 90         String className = point.getTarget().getClass().getName();
 91         // 方法的參數
 92         Object[] params = point.getArgs();
 93 
 94         StringBuilder paramsBuf = new StringBuilder();
 95         for (Object arg : params) {
 96             paramsBuf.append(arg);
 97             paramsBuf.append("&");
 98         }
 99         // 處理log。。。。
100         log.info("[X用戶]執行了[" + aLog.operation() + "],類:" + className + ",方法名:" + methodName + ",參數:"
101                 + paramsBuf.toString());
102 
103     }
104 
105     @AfterThrowing(pointcut = "entryPoint()", throwing = "e")
106     public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
107         // 通過request獲取登陸用戶信息
108         // HttpServletRequest request = ((ServletRequestAttributes)
109         // RequestContextHolder.getRequestAttributes()).getRequest();
110         try {
111             String targetName = joinPoint.getTarget().getClass().getName();
112             String className = joinPoint.getTarget().getClass().getName();
113             String methodName = joinPoint.getSignature().getName();
114             Object[] arguments = joinPoint.getArgs();
115             Class<?> targetClass = Class.forName(targetName);
116             Method[] methods = targetClass.getMethods();
117             String operation = "";
118             for (Method method : methods) {
119                 if (method.getName().equals(methodName)) {
120                     Class<?>[] clazzs = method.getParameterTypes();
121                     if (clazzs.length == arguments.length) {
122                         operation = method.getAnnotation(ServiceLog.class).operation();
123                         break;
124                     }
125                 }
126             }
127 
128             StringBuilder paramsBuf = new StringBuilder();
129             for (Object arg : arguments) {
130                 paramsBuf.append(arg);
131                 paramsBuf.append("&");
132             }
133 
134             log.info("異常方法:" + className + "." + methodName + "();參數:" + paramsBuf.toString() + ",處理了:" + operation);
135             log.info("異常信息:" + e.getMessage());
136         } catch (Exception ex) {
137             log.error("異常信息:{}", ex.getMessage());
138         }
139     }
  • 寫AOP測試功能
 1 public interface ILogService {
 2 
 3     public boolean insert(Map<String, Object> params, String id);
 4 
 5     public boolean update(String name, String id);
 6 
 7     public boolean delete(String id);
 8 
 9     public boolean doError(String id);
10 }
 1 @Service
 2 public class TestServiceImp implements ILogService {
 3 
 4     @ServiceLog(operation = "新增用戶信息測試操作。。。。。")
 5     @Override
 6     public boolean insert(Map<String, Object> params, String id) {
 7         return false;
 8     }
 9 
10     @ServiceLog(operation = "更新用戶信息操作....")
11     @Override
12     public boolean update(String name, String id) {
13         return false;
14     }
15 
16     @ServiceLog(operation = "刪除操作。。。。")
17     @Override
18     public boolean delete(String id) {
19         return false;
20     }
21 
22     @ServiceLog(operation = "異常操作測試", level = LogType.ERROR)
23     @Override
24     public boolean doError(String id) {
25         try {
26             @SuppressWarnings("unused")
27             int i = 1 / 0;
28         } catch (Exception e) {
29             throw new RuntimeException(e.getMessage());
30         }
31         return false;
32     }
33 
34 }
  • 編寫SpringBoot測試類,並展示結果
 1 @RunWith(SpringRunner.class)
 2 @SpringBootTest
 3 public class DemoSpringbootAopLogApplicationTests {
 4 
 5     @Autowired
 6     ILogService logService;
 7 
 8     @Test
 9     public void contextLoads() {
10         Map<String, Object> params = new HashMap<>();
11         params.put("key1", "v1");
12         params.put("key2", "v2");
13 
14         logService.insert(params, "111");
15         logService.update("king", "kang");
16         logService.delete("111");
17         logService.doError("111");
18     }
19 
20 }

技術分享圖片

至此,SpringCloud+AOP搭建成功!

項目完整代碼見https://github.com/Adosker/hello

SpringCloud開發學習總結(六)—— 結合註解的AOP示例