滿懷憂思,不如先幹再說!持續高頻更新技術文章,值得持續關注哦!
一、AOP介紹
1.1、概述
AOP的全稱是Aspect Oriented Programming翻譯過來就是面向切面程式設計,它的宗旨是在不修改源代碼的前提下擴充功能,比如我們想要在代碼原有的功能上去擴充功能在沒有AOP的情況下就需要修改源代碼,很不友善程式的擴充、維護,這将是一場災難,有了AOP之後我們不用修改源代碼通過切面就可以擴充功能,怎麼了解切面呢?
比如我們想要吃肉夾馍,在沒有AOP的時候我們需要再做一個烙一個帶肉的現成的肉夾馍,有了AOP之後呢,不需要重新烙一個馍,而是在馍的中間來一刀,這個就是切面,在中間加上肉就可以了。其實AOP是對OOP的補充,讓我們開發程式變得更優雅
1.2、應用場景
1、性能檢測
2、通路控制
3、事務管理
4、緩存
5、日志子產品等
1.3、AOP優點
1、集中處理項目的業務問題抽取出來單獨編寫
2、減少代碼備援
3、提高程式的維護性和擴充性等
1.4、專業術語
1、通知(Advice)
就是擴充的功能,比如我們的程式中需要添加日志,事務等功能,編寫該功能的方法就是通知,也可以稱為增強。
通知分為前置通知,後置通知,環繞通知,異常通知等,說明加在什麼位置,什麼時候調用。
2、連接配接點(JoinPoint)
可以增強的功能,比如添加、删除、修改、查詢等方法。
3、切入點(Pointcut)
實際上增強的方法,就比如我們增強添加的功能,這個添加的方法就是切入點。
4、切面(Aspect)
切入點、增強所在的那個類叫切面,這些代碼需要編寫出來,這個配置的類就是這個切面。
5、引入(introduction)
允許我們向現有的類添加新方法屬性。這不就是把切面(也就是新方法屬性:通知定義的)用到目标類中嗎。
6、目标(target)
引入中所提到的目标類,也就是要被通知的對象,也就是真正的業務邏輯,他可以在毫不知情的情況下,被咱們織入切面。而自己專注于業務本身的邏輯。
7、代理(proxy)
AOP都是通過代理模式實作
8、織入(weaving)
把切面應用到目标對象來建立新的代理對象的過程。一共有3種方式,spring采用的是運作時織入
二、實作
2.1、實作方式
在Spring中使用aspectj實作AOP操作,注意aspectj并不是Spring中的一部分,隻是和Spring一起使用,Spring2.x之後支援對aspectj的支援。使用aspectj對AOP的操作實作有xml配置和注解兩種方式
2.2、pom依賴
添加aop和aspectj依賴
<!--aop依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.19</version>
</dependency>
<!-- aspectj支援 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
2.3、xml檔案實作方式
2.3.1、業務類
package com.stt.service;
/**
操作使用者的Dao層
*/
public class UserService {
//添加使用者功能
public void addUser(){
System.out.println("添加使用者");
}
//添加使用者功能
public void deleteUser(){
System.out.println("删除使用者");
}
//添加使用者功能
public void updateUser(){
System.out.println("修改使用者");
}
//添加使用者功能
public void queryUser(){
System.out.println("查詢使用者");
}
}
2.3.2、增強類
package com.stt.advice;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 使用者的日志類,在對使用者進行修改操作時添加上時間
*/
public class UserLog {
/**
* 前置通知:即在做增删改操作前調用該方法
* 作用:生成時間
*/
public void getTime(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
System.out.println("目前時間為"+time);
}
/**
* 後置通知:即在做增删改操作後調用該方法
* 作用:提示操作成功
*/
public void success(){
System.out.println("操作成功");
}
}
2.3.3、applicationContext.xml
本來對使用者的操作隻列印對應的資訊,現在操作增删前會列印時間,操作會輸出成功
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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 id="userService" class="com.stt.service.UserService"></bean>
<!--建立增強類對象-->
<bean id="userlog" class="com.stt.advice.UserLog"></bean>
<!--配置aop-->
<aop:config>
<!--配置切入點,就是哪些方法要進行增強,這裡需要寫表達式
execution(<通路修飾符>?<傳回值類型><方法名>(<參數>)<異常>)
1. execution (* com.stt.service.UserService.add*(..)) UserService類中以add開頭的方法
2. execution (* com.stt.service.UserService.*(..))UserService類中的所有方法
3. execution (* *.*(..))所有方法
4. execution (* save*(..))比對所有save開頭的方法
......
多個表達式間使用 or 隔開
-->
<aop:pointcut id="pointcut1" expression="execution(* com.stt.service.UserService.addUser(..)) or
execution(* com.stt.service.UserService.updateUser(..)) or
execution(* com.stt.service.UserService.deleteUser(..))"></aop:pointcut>
<!--配置切面
将增強使用在切入點的過程
-->
<aop:aspect ref="userlog">
<!--前置通知使用aop before标簽
method:填寫增強類中的方法
pointcut-ref:填寫上班切入點的id
-->
<aop:before method="getTime" pointcut-ref="pointcut1"></aop:before>
<!--後置通知使用after-->
<aop:after method="success" pointcut-ref="pointcut1"></aop:after>
</aop:aspect>
</aop:config>
</beans>
2.3.4、測試
調用的是addUser方法但是該方法前後後有對應資料輸出就是我們使用aop配置的,并沒有修改UserService的源代碼隻是定義增強類和增強方法,使用xml配置檔案将功能添加上去,極大提升擴充性和維護性。
2.4、注解實作
2.4.1、業務類
package com.stt.service;
import org.springframework.stereotype.Service;
/**
操作使用者的Service層
*/
@Service("userService")
public class UserService {
//添加使用者功能
public void addUser(){
System.out.println("添加使用者");
}
//添加使用者功能
public void deleteUser(){
System.out.println("删除使用者");
}
//添加使用者功能
public void updateUser(){
System.out.println("修改使用者");
}
//添加使用者功能
public void queryUser(){
System.out.println("查詢使用者");
}
}
2.4.2、增強類
package com.stt.advice;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 使用者的日志類,在對使用者進行修改操作時添加上時間
* 添加@Aspect注解
*/
@Aspect
@Component("userLog")
public class UserLog {
/**
* 前置通知:即在做增删改操作前調用該方法
* 作用:生成時間
*/
@Before(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
" execution(* com.stt.service.UserService.updateUser(..)) || " +
" execution(* com.stt.service.UserService.deleteUser(..))")
public void getTime(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
System.out.println("目前時間為"+time);
}
/**
* 後置通知:即在做增删改操作後調用該方法
* 作用:提示操作成功
*/
@After(value = "execution(* com.stt.service.UserService.addUser(..)) || " +
" execution(* com.stt.service.UserService.updateUser(..)) || " +
" execution(* com.stt.service.UserService.deleteUser(..))")
public void success(){
System.out.println("操作成功");
}
}
2.4.3、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!--開啟注解掃描-->
<context:component-scan base-package="com.stt"/>
<!--開啟aop操作-->
<aop:aspectj-autoproxy/>
</beans>
2.4.4、測試
三、AOP原理
3.1、概述
Spring中AOP的實作方式其實是代理模式,代理模式是給某一個對象提供一個代理對象,并由代理對象控制對原對象的引用。通俗的來講代理模式就是我們生活中常見的中介。代理模式分為靜态代理和動态代理。靜态代理是由程式員建立或特定工具自動生成源代碼,再對其編譯。在程式運作之前,代理類.class檔案就已經被建立了。動态代理是在程式運作時通過反射機制動态建立的。
3.2、為什麼使用代理模式
中介隔離作用:在某些情況下,一個客戶類不想或者不能直接引用一個委托對象,而代理類對象可以在客戶類和委托對象之間起到中介的作用,其特征是代理類和委托類實作相同的接口。
開閉原則,增加功能:代理類除了是客戶類和委托類的中介之外,我們還可以通過給代理類增加額外的功能來擴充委托類的功能,這樣做我們隻需要修改代理類而不需要再修改委托類,符合代碼設計的開閉原則。代理類主要負責為委托類預處理消息、過濾消息、把消息轉發給委托類,以及事後對傳回結果的處理等。代理類本身并不真正實作服務,而是同過調用委托類的相關方法,來提供特定的服務。真正的業務功能還是由委托類來實作,但是可以在業務功能執行的前後加入一些公共的服務。例如我們想給項目加入緩存、日志這些功能,我們就可以使用代理類來完成,而沒必要打開已經封裝好的委托類。
3.3、靜态代理
3.3.1、接口
package com.stt.service;
/**
* 定義接口
*/
public interface IPersonService {
void speak();
}
3.3.2、實作類
package com.stt.service.impl;
import com.stt.service.IPersonService;
/**
實作類
*/
public class PersonService implements IPersonService {
public void speak() {
System.out.println("君不見,高堂明鏡悲白發,朝如青絲暮成雪。");
}
}
3.3.3、代理對象
package com.stt.service.impl;
import com.stt.service.IPersonService;
/**
* ClassName: PersonServiceProxy
* Description:
* date: 2019/10/17 0017 下午 20:31
*
* @author stt
* @since JDK 1.8
*/
public class PersonServiceProxy implements IPersonService {
private IPersonService personService;
public PersonServiceProxy(final IPersonService personService){
this.personService = personService;
}
public void speak() {
System.out.println("君不見,黃河之水天上來,奔流到海不複回。");
personService.speak();
System.out.println("人生得意須盡歡,莫使金樽空對月。\n" +
"天生我材必有用,千金散盡還複來。\n" +
"烹羊宰牛且為樂,會須一飲三百杯。\n" +
"岑夫子,丹丘生,将進酒,杯莫停。\n" +
"與君歌一曲,請君為我傾耳聽。(傾耳聽 一作:側耳聽)\n" +
"鐘鼓馔玉不足貴,但願長醉不複醒。(不足貴 一作:何足貴;不複醒 一作:不願醒/不用醒)\n" +
"古來聖賢皆寂寞,惟有飲者留其名。(古來 一作:自古;惟 通:唯)\n" +
"陳王昔時宴平樂,鬥酒十千恣歡谑。\n" +
"主人何為言少錢,徑須沽取對君酌。\n" +
"五花馬,千金裘,呼兒将出換美酒,與爾同銷萬古愁。");
}
}
3.3.4、測試
package com.stt.test;
import com.stt.pojo.Person;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import com.stt.service.impl.PersonServiceProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* ClassName: SpringTest
*/
public class SpringTest {
public static void main(String[] args) {
//建立PersonService對象
PersonService personService = new PersonService();
personService.speak();
//建立代理對象
PersonServiceProxy personServiceProxy = new PersonServiceProxy(personService);
personServiceProxy.speak();
}
}
3.3.5、靜态代理總結
優點:可以做到在符合開閉原則的情況下對目标對象進行功能擴充。
缺點:我們得為每一個服務都得建立代理類,工作量太大,不易管理。同時接口一旦發生改變,代理類也得相應修改。
3.4、動态代理
3.4.1、特點
1、不需要生成實作接口
2、使用JDK的API在記憶體中建構代理對象
3.4.2、代理類
package com.stt.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* PersonService代理對象
*/
public class PersonServiceProxy implements InvocationHandler {
//業務類對象
private Object target;
public PersonServiceProxy(Object target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println("invoke開始");
result = method.invoke(target,args);
System.out.println("invoke結束");
return result;
}
}
3.4.3、測試
package com.stt.test;
import com.stt.pojo.Person;
import com.stt.proxy.PersonServiceProxy;
import com.stt.service.IPersonService;
import com.stt.service.UserService;
import com.stt.service.impl.PersonService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Proxy;
/**
* ClassName: SpringTest
*/
public class SpringTest {
public static void main(String[] args) {
//被代理對象
PersonService personService = new PersonService();
//代理對象
PersonServiceProxy serviceProxy = new PersonServiceProxy(personService);
//擷取類加載器
ClassLoader classLoader = personService.getClass().getClassLoader();
//擷取該類的接口
Class<?>[] interfaces = personService.getClass().getInterfaces();
IPersonService iPersonService = (IPersonService)Proxy.newProxyInstance(classLoader, interfaces, serviceProxy);
iPersonService.speak();
}
}
3.4.4、總結
1、實作InvocationHandler接口重寫invoke方法
2、建立代理對象使用Proxy類的newProxyInstance方法,傳入實作類類加載器,接口和代理類的對象
不錯記得三連哦,收藏等于學會,還不快快收藏!