Spring 通過註解了解AOP

2021-08-13 20:37:01 字數 3241 閱讀 5167

先拋開那些複雜的的名詞,我們來看個簡單的例子。假如我們在編寫乙個**

**主頁的controller

@controller

public

class

indexcontroller

}

aop切面

import org.aspectj.lang.annotation.after;

import org.aspectj.lang.annotation.aspect;

import org.aspectj.lang.annotation.before;

import org.springframework.stereotype.component;

@aspect

//用@aspect註解宣告整個類是乙個切面

@component

//一定要將切面注入

public

class

aop

//用@after註解宣告乙個切點,在目標方法執行完後執行

@after("execution(* com.myzhihu.controller.indexcontroller.index(..))")

public

void

after()

}

那麼我們每次訪問localhost:8080/index 時 控制台都會輸出

這種在執行時,動態地將**切入到類的指定方法、指定位置上的程式設計思想就是面向切面的程式設計。

aspectj註解宣告切點有如下通知方法

@before 在目標方法呼叫之前執行

@around 將目標方法封裝起來

@after 在目標方法返回或者丟擲異常後呼叫

@afterthrowing 在目標方法丟擲異常後呼叫

@afterreturning 在目標方法返回後呼叫

切點就是我們想把切面程式切入到**去.

我們看到,相同的切點表示式我們重複了兩遍,好在我們可以使用@pointcut來定義可重用的切點

@aspect

@component

public

class

aop

@before("index()")

public

void

before()

@after("index()")

public

void

after()

}

index()方法並不重要,他是個空的,只是供給@pointcut依附。

1.execution匹配具體方法

execution也支援萬用字元

你也可以用execution(* com.myzhihu.controller.indexcontroller.*(..))來表示indexcontroller類中的任何方法都做切點。

也可以用execution(* com.myzhihu.controller.controller.(..))來表示用controller包下所有以controller結尾的類中的所有方法做切點。

2.within來匹配包和類

//&& 代表and  within裡代表myzhihu包下所有子包的方法被呼叫時

@pointcut("execution(* com.myzhihu.controller.indexcontroller.index(..)) && within(com.myzhihu.*)")

public

void

test(){}

3.引數匹配

//匹配任何以index開頭並且只有乙個int型引數的方法

@pointcut("execution(* *..index*(int))")

public

void

argsdemo1(){}

//匹配任何只有乙個int型引數的方法

@pointcut("args(int)")

public

void

argsdemo2(){}

//匹配任何以index開頭並且第乙個引數為int型的方法

@pointcut("execution(* *..index*(int,..))")

public

void

argsdemo3(){}

//匹配任何第乙個引數為int型的方法

@pointcut("args(int,..)")

public

void

argsdemo2(){}

4.匹配註解public

void

annotationdemo(){}

//匹配標註有@controller的類底下的方法(注意,註解必須是類級別)

@pointcut("@within(org.springframework.stereotype.controller)")

public

void

withindemo(){}

//匹配標註有controller的類底下的方法,註解的retentionpolicy必須為runtime

@pointcut("@target(org.springframework.stereotype.controller)")

public

void

targetdemo(){}

//匹配傳入的引數類標註有@component的方法

@pointcut("@args(org.springframework.stereotype.component)")

public

void

argsdemo(){}

aop是對物件導向程式設計的乙個強大的補充。通過aspectj,我們可以把之前分散在應用各處的行為放入可重用的模組中,這有效的減少了**冗餘,讓我們的類關注自身的主要功能。

而且可以無侵入的為**新增功能。

Spring之通過註解方式實現AOP

乙個簡單的通過註解方式實現aop 通過aop統計方法呼叫耗時 目錄結構 具體類如下 配置類 package com.infuq.springaop import org.springframework.context.annotation.componentscan import org.sprin...

Spring的註解 了解一些些註解流程3

擴充套件原理 1 beanfactorypostprocessor beanpostprocessor bean後置處理器,bean建立物件初始化前後進行攔截工作的 beanfactorypostprocessor beanfactory的後置處理器,在beanfactory標準初始化之後呼叫 所有...

Spring 通過註解方式實現AOP切面程式設計

spring 切面程式設計的目的是實現 的業務邏輯的解耦。切面程式設計用於諸如日誌記錄,事務處理,等非業務性的邏輯操作。目前spring的aop只能應用於方法層級上,無法在類 成員欄位等層級上操作。以下是srping的aop程式設計分為註解方式和xml配置方式。以下過程詳細說明了通過註解方式實現ao...