1. 程式人生 > 其它 >leetcode 451. Sort Characters By Frequency 根據字元出現頻率排序

leetcode 451. Sort Characters By Frequency 根據字元出現頻率排序

AOP

為什麼要用AOP:

  • 需要對 原生的程式碼 進行 增強 批處理

  • 降低耦合度

  • 不能改變原有的程式碼

  • 例子

    1. 事務

    2. 快取

    3. 許可權

    4. 日誌

    5. 分散式鎖

本質:不改變原有的程式碼和呼叫方式,增加程式碼的功能

核心: 動態代理

  1. JDK (介面)

  2. cglib (代理類)

匯入依賴

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.20</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.3.20</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="com.qf.aop"/>
    <!--    spring對aop支援-->
    <aop:aspectj-autoproxy/>
</beans>

概念:切面 切入點 通知(五種)

主要註解

@Aspect: 該註解是把此類宣告為一個切面類

  • 寫在類上宣告切面類

@PointCut: 該註解是宣告一個公用的切入點表示式(通知行為的註解的都可以直接拿來複用)

本質上就是將方法攔截下來 滿足判斷條件後 執行後面的註解下的程式碼

  • 常用引數

    • execution()

      parameters pattern:指定方法引數(宣告的型別),(..)代表所有引數,(*)代表一個引數,(*,String)代表第一個引數為任何值,第二個為String型別.

      例子:

      任意公共方法的執行:
      execution(public * *(..))
      任何一個以“set”開始的方法的執行:
      execution(* set*(..))
      AccountService 介面的任意方法的執行:
      execution(* com.xyz.service.AccountService.*(..))
      定義在service包裡的任意方法的執行:
      execution(* com.xyz.service.*.*(..))
      定義在service包和所有子包裡的任意類的任意方法的執行:
      execution(* com.xyz.service..*.*(..))
      定義在pointcutexp包和所有子包裡的JoinPointObjP2類的任意方法的執行:
      execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
      
    • @annotation

      指定對應的自定義註解類 帶有對應註解的方法都會被攔截

@Before: 該註解是宣告此方法為前置通知 (目標方法執行前就會先執行被此註解標註的方法)

@After: 該註解是宣告此方法為後置通知 (目標方法執行完之後就會執行被此註解標註的方法) 不管有沒有異常都會執行

@AfterReturning: 該註解是宣告此方法為返回通知 (目標方法正常執行返回後就會執行被此註解標註的方法) 也就是執行完沒有異常時

@AfterThrowing: 該註解是宣告此方法為異常通知 (目標方法在執行出現異常時就會執行被此註解標註的方法)

@Around: 該註解是環繞通知是動態的,可以在前後都設定執行

  • 可以同時實現以上所有的功能