Day03:AOP

1、橫切

  • 連接點(diǎn):應(yīng)用通知的所有點(diǎn)
  • 通知:切面是什么及何時(shí)使用
  • 切點(diǎn):通知被應(yīng)用的具體位置(哪些連接點(diǎn))
  • 切面:通知和切點(diǎn)的結(jié)合

2、Spring的AOP

2.1 AOP支持類型

  • 基于代理的經(jīng)典Spring AOP
  • 純POJO切面
  • @AspectJ注解驅(qū)動(dòng)的切面
  • 注入式AspectJ切面

前三中,構(gòu)建在動(dòng)態(tài)代理的基礎(chǔ)上,只支持方法攔截

2.1.1 經(jīng)典Spring AOP

笨重復(fù)雜,直接使用ProxyFactoryBean

2.1.2 POJO切面

  • 使用@Aspect注解類,在方法上注解,同時(shí)該類也是普通的類
    @Before("execution(* concert.Performance.perform(..))")
    方法上,每個(gè)方法都需要切點(diǎn)表達(dá)式
    還包括 @After、 @AfterReturning、 @AfterThrowing、 @Around[通知方法將目標(biāo)方法封裝起來]、 @Before
  • 通過 @ Poingcut 注解定義命名的切點(diǎn),然后調(diào)用
    @Poingcut("execution(** concert.Performance.perform(..))") public void performace(){} @Before("performance()")

2.2 配置類級(jí)別的自動(dòng)代理

2.2.1在JavaConfig中,注解

@Configuration @EnableAspectJAutoProxy @ComponentScan

2.2.2 xml中配置

  • 引入aop命名空間 xmlns:aop="http://www.springframework.org/schema/aop" xml:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aopsoring-aop.xsd
  • <aop:aspectj-autoproxy /> <bean class="concert.Audidence" />

2.3 環(huán)繞通知

  • 示例,使用 @Around 注解
    `@Around("performance()")
    public void wtachPerformance(ProceddingJoinPoint jp) {
    jp.proceed();//不調(diào)用會(huì)阻塞被通知方法的調(diào)用

}`

2.4 帶參數(shù)的通知

`@Poingcut("execution(** soundsystem.CompactDisc.playTrack(int)) && args(trackNumber) ")
public void trackPlayed(int trackNumber){}

@Before("trackPlayed(trackNumber)")
public void countTrack(int trackNumber) {
//修改trackNumber的值
}`
//表達(dá)式分解:
*:返回任意類型
soundsystem.CompactDise:方法所屬的類型
playTrack(int)) :方法及接受的參數(shù)類型
args(trackNumber) :指定參數(shù)

3、注解加新功能

3.1 添加新的方法(接口)

給現(xiàn)有的bean添加接口,通過代理暴露新接口,該方法被調(diào)用時(shí),代理將此調(diào)用委托給實(shí)現(xiàn)了新接口的其他對(duì)象
@Aspect public class EncoreableIntroducer { @DeclareParents(value="concert.Performance+", defaultImpl=DefaultEncorealbe.class) public static Encoreable encoreable; }
//解釋說明
value:指定要引入該接口的bean,+代表它的所有子類型,不是它本身
defaultImpl:引入功能的實(shí)現(xiàn)類
@DeclareParents注解:要引入的接口

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容