AOP-02
4.問題提出
在上一篇的MyProxyProvider類中,我們的輸出陳述句功能比較弱,在實際開發中,我們希望是以一個方法的形式,嵌入到真正執行的目標方法前,怎么辦?
1.使用土方法解決
需求分析:使用土方法解決前面的問題,后面使用spring的aop組件完成
改進MyProxyProvider:
主要是對前置/回傳/例外/最終通知的代碼進行封裝,封裝到不同的方法中進行呼叫,
package com.li.aop.proxy3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
/**
* @author 李
* @version 1.0
* 回傳一個動態代理物件,可以執行被代理的物件的方法
*/
public class MyProxyProvider {
//定義要執行的目標物件,該物件需要實作 SmartAnimal介面
private SmartAnimal target_animal;
//構造器
public MyProxyProvider(SmartAnimal target_animal) {
this.target_animal = target_animal;
}
//定義一個方法,在目標物件執行前執行
public void before(Method method, Object[] args) {
System.out.println("before-方法執行開始-日志-方法名-" + method.getName() +
"-引數 " + Arrays.toString(args));//AOP的角度看,是一個橫切關注點-前置通知
}
//定義一個方法,在目標物件執行后行
public void after(Method method, Object result) {
System.out.println("after-方法執行正常結束-日志-方法名-" + method.getName()
+ "-結果 result = " + result);//也是一個橫切關注點-回傳通知
}
//定義方法回傳代理物件,該代理物件可以執行目標物件
public SmartAnimal getProxy() {
//(1)先得到類加載器物件
ClassLoader classLoader = target_animal.getClass().getClassLoader();
//(2)得到要執行的目標物件的介面資訊
Class<?>[] interfaces = target_animal.getClass().getInterfaces();
//(3)使用匿名內部類 創建 InvocationHandler物件
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
before(method, args);
//使用反射真正呼叫方法
result = method.invoke(target_animal, args);
after(method, result);
} catch (Exception e) {
//如果反射出現例外,就會進入到catch塊
System.out.println("方法執行例外-日志-方法名" + method.getName()
+ "-例外型別=" + e.getClass().getName());//橫切關注點-例外通知
e.printStackTrace();
} finally {//無論是否出現例外,最終都會執行到 finally{}
//也是一個橫切關注點-最終通知
System.out.println("方法最終結束-日志-方法名-" + method.getName());
}
return result;
}
};
//創建代理物件
SmartAnimal proxy = (SmartAnimal) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
return proxy;
}
}
2.對土方法進行解耦-開發簡易的AOP類
上面的代碼因為前后置等處理方法都寫在同一個類中,造成代碼耦合度高的問題,因此,更好的解決方法是新建一個類MyAOP,在該類中進行處理方法的撰寫,然后在MyProxyProvider類中呼叫該類的方法,
MyAOP類:
package com.li.aop.proxy3;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author 李
* @version 1.0
* 自己寫的一個極簡AOP類
*/
public class MyAOP {
//定義一個方法,在目標物件執行前執行
public static void before(Method method, Object[] args) {
System.out.println("MyAOP-方法執行開始-日志-方法名-" + method.getName() +
"-引數 " + Arrays.toString(args));//前置通知
}
//定義一個方法,在目標物件執行后行
public static void after(Method method, Object result) {
System.out.println("MyAOP-方法執行正常結束-日志-方法名-" + method.getName()
+ "-結果 result = " + result);//回傳通知
}
}
3.再次分析-提出Spring AOP
使用上面的辦法仍存在一些問題:
- 不夠靈活:假設被代理物件有很多方法,而我們只想僅對其中一個方法進行處理,當前的代碼還不能實作這個需求
- 復用性差:假如有一個新的介面USBInterface,Phone類實作了這個介面,現在我們想要Phone類去呼叫之前MyAOP中的方法,但MyAOP類的方法是根據之前的SmartAnimal介面的方法寫的,因此不能很好的適用于新的介面及其實作類
- 硬編碼:沒有注解和反射的支撐
5.AOP的基本介紹
1.什么是AOP?
官方檔案:核心技術 (spring.io)
AOP全稱:aspect oriented programming,即面向切面編程,
AOP 是一種編程思想,是面向物件編程(OOP)的一種補充,面向物件編程將程式抽象成各個層次的物件,而面向切面編程是將程式抽象成各個切面,
2.AOP和OOP的區別:
OOP 針對業務處理程序的物體及其屬性和行為進行抽象封裝,以獲得更加清晰高效的邏輯單元劃分,
而 AOP 則是針對業務處理程序中的切面進行提取,它所面對的是處理程序中的某個步驟或階段,以獲得邏輯程序中各部分之間低耦合性的隔離效果,
這兩種設計思想在目標上有著本質的差異:
面向目標不同:簡單來說 OOP 是面向名詞領域,AOP 面向動詞領域,
思想結構不同:OOP 是縱向結構,AOP 是橫向結構,
注重方面不同:OOP 注重業務邏輯單元的劃分,AOP 偏重業務處理程序中的某個步驟或階段,
aop通過動態代理+反射的方式,對被代理物件的方法進行呼叫,
這個被代理物件的方法的呼叫程序,會拆分成幾個橫切關注點:
- 方法呼叫前
- 方法呼叫
- 方法呼叫后
- 例外位置(catch塊)
- 方法最終呼叫位置(finally塊)
如下,切面類C的不同方法f1……fn可以在不同類A,B......的方法m1,m2......執行的程序中,在方法的不同橫切關注點任意切入/呼叫,
即切面類的任意方法可以在任意類的任意方法執行的程序中,在該方法的不同橫切關注點任意切入,
3.AOP的實作方式
- 基于動態代理的方式[內置AOP實作]
- 使用框架aspectj來實作
6.AOP編程快速入門
6.1基本說明
這里使用框架aspectj來實作:
-
引入核心的aspect包
-
在切面類中宣告通知方法
- 前置通知:@Before
- 回傳通知:@AfterReturning
- 例外通知:@AfterThrowing
- 后置通知:@After
- 環繞通知:@Around
-
五種通知和前面寫的動態代理類方法的對應關系:
6.2快速入門實體
使用aop編程的方式,來實作手寫的動態代理案例的效果,以上一篇的3.1為例子:
需求說明:有一個SmartAnimal介面,可以完成簡單的加減法,要求在執行getSum()和getSub()時,輸出執行前、執行程序、執行后的日志輸出,請思考如何實作
1.匯入AOP編程需要的包
2.代碼實作
2.1SmartAnimal介面:
package com.li.aop.aspectj;
/**
* @author 李
* @version 1.0
*/
public interface SmartAnimal {
//求和
float getSum(float a, float b);
//求差
float getSub(float a, float b);
}
2.2SmartDog實作類:
package com.li.aop.aspectj;
import org.springframework.stereotype.Component;
/**
* @author 李
* @version 1.0
*/
//使用component注解,當spring容器啟動時,將SmartDog注入容器
@Component
public class SmartDog implements SmartAnimal {
@Override
public float getSum(float a, float b) {
float result = a + b;
System.out.println("方法內部列印 result = " + result);
return result;
}
@Override
public float getSub(float a, float b) {
float result = a - b;
System.out.println("方法內部列印 result = " + result);
return result;
}
}
2.3SmartAnimalAspect切面類:
package com.li.aop.aspectj;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* @author 李
* @version 1.0
* 切面類,類似之前寫的 MyProxyProvider,但是功能比它強大得多
*/
@Aspect //表示一個切面類[底層自動注入切面編程的支撐(動態代理+反射+動態系結)]
@Component //注入切面類到ioc容器
public class SmartAnimalAspect {
/**
* 前置通知
* 1.@Before表示前置通知,即在我們的目標物件執行方法前執行
* 2.value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(public float com.li.aop.aspectj.SmartDog.getSum(float, float))"
* 指定切入到哪個類的哪個方法 形式為:execution(訪問修飾符 回傳型別 全類名.方法名(形參串列))
* 3.f1方法就是一個切入方法,方法名隨意
* 4.JoinPoint joinPoint 在底層執行時,由AspectJ切面框架,給切入方法傳入joinPoint連接點物件
* 通過切面方法,可以獲取你想要的資訊
*
* @param joinPoint
*/
@Before(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(public float com.li.aop.aspectj.SmartDog.getSum(float, float))")
public void f1(JoinPoint joinPoint) {
//通過連接點物件joinPoint 拿到方法簽名
Signature signature = joinPoint.getSignature();
System.out.println("切面類f1()-方法執行開始-日志-方法名-" + signature.getName() +
"-引數 " + Arrays.toString(joinPoint.getArgs()));
}
//回傳通知:把 f2方法切入到目標物件方法正常執行完畢后的位置
@AfterReturning(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(public float com.li.aop.aspectj.SmartDog.getSum(float, float))")
public void f2(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
System.out.println("切面類f2()-方法執行正常結束-日志-方法名-" + signature.getName());
}
//例外通知:把 f3方法切入到目標物件方法出現例外后的catch塊位置
@AfterThrowing(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(public float com.li.aop.aspectj.SmartDog.getSum(float, float))")
public void f3(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
System.out.println("切面類f3()-方法執行例外-日志-方法名-" + signature.getName());
}
//最終通知:把 f4方法切入到目標物件方法執行后的位置,無論有無出現例外都會執行
@After(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(public float com.li.aop.aspectj.SmartDog.getSum(float, float))")
public void f4(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
System.out.println("切面類f4()-方法最終執行完畢-日志-方法名-" + signature.getName());
}
}
2.4配置容器檔案beans07.xml:
<?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.li.aop.aspectj"/>
<!--一定要開啟基于注解的 AOP 功能-->
<aop:aspectj-autoproxy/>
</beans>
2.5測驗類:
package com.li.aop.aspectj;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;
/**
* @author 李
* @version 1.0
* 測驗類
*/
public class AopAspectjTest {
@Test
public void smartDogTestByAspectj() {
//得到Spring容器
ApplicationContext ioc =
new ClassPathXmlApplicationContext("beans07.xml");
//通過介面型別來獲得注入的SmartDog物件(實際上是代理物件proxy)
SmartAnimal smartAnimal = ioc.getBean(SmartAnimal.class);
//class com.sun.proxy.$Proxy15
//System.out.println("smartAnimal的運行型別=" + smartAnimal.getClass());
smartAnimal.getSum(100, 48);
}
}
測驗結果:
6.3細節說明
-
關于切面類方法命名可以自己規范一下
-
切入運算式的更多配置,比如使用模糊配置
形式為:execution(訪問修飾符 回傳型別 全類名.方法名(形參串列))
@Before(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(* com.li.aop.aspect.SmartDog.*(..))") -
下面表示所有訪問權限,所有包下所有類的所有方法(前提是基于動態代理的類),都會被執行前置通知方法
@Before(value = "https://www.cnblogs.com/liyuelian/archive/2023/01/24/execution(* *.*(..))") -
spring容器開啟了基于注解的AOP功能
<aop:aspectj-autoproxy/>,獲取注入的物件則需要以介面的型別來獲取,因為你注入的物件.getClass()已經是代理型別了! -
spring容器開啟了基于注解的AOP功能,也可以通過id來獲取注入的物件,但也要轉成介面型別來獲取,
6.4練習
- 有一個介面USBInterface,該介面有一個方法work
- 寫出實作子類Phone和Camera
- 寫一個切面類,在該切面類中寫一個方法(可輸出日志資訊)等作為前置通知,在Phone和Camera物件執行work方法前呼叫
- 其他通知,如回傳通知,例外通知,后置通知,也可以加入
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542382.html
標籤:其他
上一篇:學習筆記——Linux中搜索查找類命令;壓縮和解壓類;Linux掛載和卸載;行程執行緒類命令;RPM;YUM
下一篇:淺談PHP設計模式的組合模式
