學習的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾。各位小伙伴,如果您:
想系統(tǒng)/深入學習某技術知識點…
一個人摸索學習很難堅持,想組團高效學習…
想寫博客但無從下手,急需寫作干貨注入能量…
熱愛寫作,愿意讓自己成為更好的人…
前言
一、基于注解的AOP
1、技術說明
2、準備工作
3、創(chuàng)建切面類并配置
4、各種通知
5、切入點表達式語法
6、重用切入點表達式
7、獲取通知的相關信息
8、環(huán)繞通知
9、切面的優(yōu)先級
二、基于XML的AOP
1、準備工作
2、實現(xiàn)
一、基于注解的AOP
1、技術說明
- 動態(tài)代理分為JDK動態(tài)代理和cglib動態(tài)代理
- 當目標類有接口的情況使用JDK動態(tài)代理和cglib動態(tài)代理,沒有接口時只能使用cglib動態(tài)代理
- JDK動態(tài)代理動態(tài)生成的代理類會在com.sun.proxy包下,類名為$proxy1,和目標類實現(xiàn)相同的接口
- cglib動態(tài)代理動態(tài)生成的代理類會和目標在在相同的包下,會繼承目標類
- 動態(tài)代理(InvocationHandler):JDK原生的實現(xiàn)方式,需要被代理的目標類必須實現(xiàn)接口。因為這個技術要求代理對象和目標對象實現(xiàn)同樣的接口(兄弟兩個拜把子模式)。
- cglib:通過繼承被代理的目標類(認干爹模式)實現(xiàn)代理,所以不需要目標類實現(xiàn)接口。
- AspectJ:是AOP思想的一種實現(xiàn)。本質上是靜態(tài)代理,將代理邏輯“織入”被代理的目標類編譯得到的字節(jié)碼文件,所以最終效果是動態(tài)的。weaver就是織入器。Spring只是借用了AspectJ中的注解。
2、準備工作
①添加依賴
在IOC所需依賴基礎上再加入下面依賴即可:
<dependencies>
<!--spring context依賴-->
<!--當你引入Spring Context依賴之后,表示將Spring的基礎依賴引入了-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
<!--spring aop依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.0.2</version>
</dependency>
<!--spring aspects依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.0.2</version>
</dependency>
<!--junit5測試-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
</dependency>
<!--log4j2的依賴-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.19.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.19.0</version>
</dependency>
</dependencies>
②準備被代理的目標資源
接口:
public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}
實現(xiàn)類:
@Component
public class CalculatorImpl implements Calculator {
@Override
public int add(int i, int j) {
int result = i + j;
System.out.println("方法內部 result = " + result);
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
System.out.println("方法內部 result = " + result);
return result;
}
@Override
public int mul(int i, int j) {
int result = i * j;
System.out.println("方法內部 result = " + result);
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
System.out.println("方法內部 result = " + result);
return result;
}
}
3、創(chuàng)建切面類并配置
// @Aspect表示這個類是一個切面類
@Aspect
// @Component注解保證這個切面類能夠放入IOC容器
@Component
public class LogAspect {
@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}
@After("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->后置通知,方法名:"+methodName);
}
@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名:"+methodName+",結果:"+result);
}
@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->異常通知,方法名:"+methodName+",異常:"+ex);
}
@Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
Object result = null;
try {
System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行之前");
//目標對象(連接點)方法的執(zhí)行
result = joinPoint.proceed();
System.out.println("環(huán)繞通知-->目標對象方法返回值之后");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("環(huán)繞通知-->目標對象方法出現(xiàn)異常時");
} finally {
System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行完畢");
}
return result;
}
}
在Spring的配置文件中配置:
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--
基于注解的AOP的實現(xiàn):
1、將目標對象和切面交給IOC容器管理(注解+掃描)
2、開啟AspectJ的自動代理,為目標對象自動生成代理
3、將切面類通過注解@Aspect標識
-->
<context:component-scan base-package="com.atguigu.aop.annotation"></context:component-scan>
<aop:aspectj-autoproxy />
</beans>
執(zhí)行測試:
public class CalculatorTest {
private Logger logger = LoggerFactory.getLogger(CalculatorTest.class);
@Test
public void testAdd(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
Calculator calculator = ac.getBean( Calculator.class);
int add = calculator.add(1, 1);
logger.info("執(zhí)行成功:"+add);
}
}
4、各種通知
- 前置通知:使用@Before注解標識,在被代理的目標方法前執(zhí)行
- 返回通知:使用@AfterReturning注解標識,在被代理的目標方法成功結束后執(zhí)行(壽終正寢)
- 異常通知:使用@AfterThrowing注解標識,在被代理的目標方法異常結束后執(zhí)行(死于非命)
- 后置通知:使用@After注解標識,在被代理的目標方法最終結束后執(zhí)行(蓋棺定論)
- 環(huán)繞通知:使用@Around注解標識,使用try…catch…finally結構圍繞整個被代理的目標方法,包括上面四種通知對應的所有位置
各種通知的執(zhí)行順序:
- Spring版本5.3.x以前:
- 前置通知
- 目標操作
- 后置通知
- 返回通知或異常通知
- Spring版本5.3.x以后:
- 前置通知
- 目標操作
- 返回通知或異常通知
- 后置通知
5、切入點表達式語法
①作用
②語法細節(jié)
-
用*號代替“權限修飾符”和“返回值”部分表示“權限修飾符”和“返回值”不限
-
在包名的部分,一個“*”號只能代表包的層次結構中的一層,表示這一層是任意的。
- 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
-
在包名的部分,使用“*…”表示包名任意、包的層次深度任意
-
在類名的部分,類名部分整體用*號代替,表示類名任意
-
在類名的部分,可以使用*號代替類名的一部分
- 例如:*Service匹配所有名稱以Service結尾的類或接口
-
在方法名部分,可以使用*號表示方法名任意
-
在方法名部分,可以使用*號代替方法名的一部分
- 例如:*Operation匹配所有方法名以Operation結尾的方法
-
在方法參數(shù)列表部分,使用(…)表示參數(shù)列表任意
-
在方法參數(shù)列表部分,使用(int,…)表示參數(shù)列表以一個int類型的參數(shù)開頭
-
在方法參數(shù)列表部分,基本數(shù)據(jù)類型和對應的包裝類型是不一樣的
- 切入點表達式中使用 int 和實際方法中 Integer 是不匹配的
-
在方法返回值部分,如果想要明確指定一個返回值類型,那么必須同時寫明權限修飾符
- 例如:execution(public int …Service.(…, int)) 正確
例如:execution( int *…Service.(…, int)) 錯誤
- 例如:execution(public int …Service.(…, int)) 正確
6、重用切入點表達式
①聲明
@Pointcut("execution(* com.atguigu.aop.annotation.*.*(..))")
public void pointCut(){}
②在同一個切面中使用
@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}
③在不同切面中使用
@Before("com.atguigu.aop.CommonPointCut.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}
7、獲取通知的相關信息
①獲取連接點信息
獲取連接點信息可以在通知方法的參數(shù)位置設置JoinPoint類型的形參
@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
//獲取連接點的簽名信息
String methodName = joinPoint.getSignature().getName();
//獲取目標方法到的實參信息
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}
②獲取目標方法的返回值
@AfterReturning中的屬性returning,用來將通知方法的某個形參,接收目標方法的返回值
@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名:"+methodName+",結果:"+result);
}
③獲取目標方法的異常
@AfterThrowing中的屬性throwing,用來將通知方法的某個形參,接收目標方法的異常
@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->異常通知,方法名:"+methodName+",異常:"+ex);
}
8、環(huán)繞通知
@Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
Object result = null;
try {
System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行之前");
//目標方法的執(zhí)行,目標方法的返回值一定要返回給外界調用者
result = joinPoint.proceed();
System.out.println("環(huán)繞通知-->目標對象方法返回值之后");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("環(huán)繞通知-->目標對象方法出現(xiàn)異常時");
} finally {
System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行完畢");
}
return result;
}
9、切面的優(yōu)先級
相同目標方法上同時存在多個切面時,切面的優(yōu)先級控制切面的內外嵌套順序。
- 優(yōu)先級高的切面:外面
- 優(yōu)先級低的切面:里面
使用@Order注解可以控制切面的優(yōu)先級:
- @Order(較小的數(shù)):優(yōu)先級高
- @Order(較大的數(shù)):優(yōu)先級低
二、基于XML的AOP
1、準備工作
參考基于注解的AOP環(huán)境文章來源:http://www.zghlxwxcb.cn/news/detail-765912.html
2、實現(xiàn)
<context:component-scan base-package="com.atguigu.aop.xml"></context:component-scan>
<aop:config>
<!--配置切面類-->
<aop:aspect ref="loggerAspect">
<aop:pointcut id="pointCut"
expression="execution(* com.atguigu.aop.xml.CalculatorImpl.*(..))"/>
<aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
<aop:after method="afterMethod" pointcut-ref="pointCut"></aop:after>
<aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
<aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
<aop:around method="aroundMethod" pointcut-ref="pointCut"></aop:around>
</aop:aspect>
</aop:config>
總結
以上就是spring之面向切面:AOP(2)的相關知識點,希望對你有所幫助。
積跬步以至千里,積怠惰以至深淵。時代在這跟著你一起努力哦!文章來源地址http://www.zghlxwxcb.cn/news/detail-765912.html
到了這里,關于spring之面向切面:AOP(2)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!