AOP概述
- Aspect Oriented Programming :面向切面編程,AOP是OOP(面向對象編程)的延續,AOP採取橫向抽取機制,可以對業務邏輯的各個部分進行隔離,使得業務邏輯各部分之間的耦合度降低,提高程序的可重用性,提高開發效率。
AOP實現原理:採用代理機制進行實現
- 1. jdk動態代理Proxy 實現 + 類接口
- 2. cglib字節碼增強 實現類
AOP術語
- 1.target:目標類,需要被代理的類。例如:UserService
- 2.Joinpoint(連接點):代理類中可能被攔截到的方法
- 3.PointCut:切入點:已經被增強的連接點。目標類中被代理的方法
- 4.Advice :通知/增強,增強的代碼。例如:after、before
- 5.Weaving:(織入):是指把增強advice應用到目標對象target來創建新的代理對象proxy的過程.6.
- 6.proxy:代理類
- 7.Aspect(切面): 是切入點pointcut和通知advice的結合組成一個特殊的面。
AOP聯盟通知類型
-
AOP聯盟爲通知Advice定義了org.aopalliance.aop.Advice 增強代碼類型
Spring按照通知 Advice 在目標類方法的連接點位置,可以分爲5類
•前置通知 org.springframework.aop.MethodBeforeAdvice 在目標方法執行前實施增強
•後置通知 org.springframework.aop.AfterReturningAdvice 在目標方法執行後實施增強
•環繞通知 org.aopalliance.intercept.MethodInterceptor 在目標方法執行前後實施增強
•異常拋出通知 org.springframework.aop.ThrowsAdvice 在方法拋出異常後實施增強
•引介通知 org.springframework.aop.IntroductionInterceptor 在目標類中添加一些新的方法和屬性
AOP全自動編程步驟
- 1.在bean中配置aop約束
-
<?xml version="1.0" encoding="UTF-8"?> <!--xmlns xml namespace:xml命名空間--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p ="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> </bean>
2.配置aop:conifg內容,把 切入點 和 通知 Advice 結合
-
<!-- 配置切面類對象--> <bean id="myAspect切面類對象名" class="com.zjc.aspect.MyAspect切面類"></bean>
-
<aop:config proxy-target-class="true"> <aop:pointcut id="myPointcut" expression="execution(* com.zjc.service.*.*(..))"/> <aop:advisor advice-ref="myAspect切面類對象名" pointcut-ref="myPointcut"></aop:advisor> </aop:config>
- proxy-target-class: 使用cglib實現代理
- expression 表達式: * 任意
- 語法:execution(修飾符 返回值 包.類.方法名(參數) throws異常)
例如 execution( * com.zjc.service. * . * (..) )
返回值 包名 類名 方法名 參數
AspectJ 通知類型
- before:前置通知(應用:各種校驗) 在方法執行前執行,如果通知拋出異常,阻止方法運行
- afterReturning:後置通知(應用:常規數據處理)方法正常返回後執行,如果方法中拋出異常,通知無法執行必須在方法執行後才執行,所以可以獲得方法的返回值。
- around:環繞通知(應用:十分強大,可以做任何事情)方法執行前後分別執行,可以阻止方法的執行必須手動執行目標方法
- afterThrowing:拋出異常通知(應用:包裝異常信息)方法拋出異常後執行,如果方法沒有拋出異常,無法執行
- after:最終通知(應用:清理現場)方法執行完畢後執行,無論方法中是否出現異常
AspectJ註解總結
- @Aspect 聲明切面,修飾切面類,從而獲得 通知。
- @Before 前置
- @AfterReturning 後置
- @Around 環繞
- @AfterThrowing 拋出異常
- @After 最終
- @PointCut 切入點修飾方法 private void xxx(){} 之後通過“方法名”獲得切入點引用
。。。。。。。。。。。待學習