文章目錄
一、AOP簡介
1、AOP基本概念
簡單的說它就是把我們程序重複的代碼抽取出來,在需要執行的時候,使用動態代理的技術,在不修改源碼的基礎上,對我們的已有方法進行增強。
2、AOP的作用及優勢
作用:在程序運行期間,不修改源碼對已有方法進行增強。
優勢:減少重複代碼;提高開發效率;維護方便
3、AOP 的實現方式
使用動態代理技術
4、AOP相關術語
(1)Joinpoint(連接點)
所謂連接點是指那些被攔截到的點。在 Spring 中,這些點指的是方法,因爲 Spring 只支持方法類型的連接點。
(2)Pointcut(切入點)
所謂切入點是指我們要對哪些 Joinpoint 進行攔截的定義。
注意:所有的切入點都是連接點,但是所有的連接點不一定都是切入點。
(3)Advice(通知/增強)
所謂通知是指攔截到 Joinpoint 之後所要做的事情就是通知。
通知的類型:前置通知,後置通知,異常通知,最終通知,環繞通知。
(4)Introduction(引介)
引介是一種特殊的通知在不修改類代碼的前提下, Introduction 可以在運行期爲類動態地添加一些方法或 Field。
(5)Target(目標對象)
代理的目標對象。
(6)Weaving(織入)
是指把增強應用到目標對象來創建新的代理對象的過程。
Spring 採用動態代理織入,而 AspectJ 採用編譯期織入和類裝載期織入。
(7)Proxy(代理)
一個類被 AOP 織入增強後,就產生一個結果代理類。
(8)Aspect(切面)
是切入點和通知(引介)的結合。
5、學習 Spring 中的 AOP 要明確的事
a、開發階段(我們做的)
編寫核心業務代碼(開發主線):大部分程序員來做,要求熟悉業務需求。
把公用代碼抽取出來,製作成通知。(開發階段最後再做)
在配置文件中,聲明切入點與通知間的關係,即切面。
b、運行階段(Spring 框架完成的)
Spring 框架監控切入點方法的執行。一旦監控到切入點方法被運行,使用代理機制,動態創建目標對象的代理對象,根據通知類別,在代理對象的對應位置,將通知對應的功能織入,完成完整的代碼邏輯運行。
6、關於代理的選擇
在 Spring 中,框架會根據目標類是否實現了接口來決定採用哪種動態代理的方式。
二、基於XML的AOP配置
1、添加依賴
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
2、IAccountService.java
public interface IAccountService {
/**
* 模擬保存賬戶
*/
void saveAccount();
/**
* 模擬更新賬戶
* @param i
*/
void updateAccount(int i);
/**
* 模擬刪除賬戶
* @return
*/
int deleteAccount();
}
3、AccountServiceImpl.java
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("執行了保存");
}
public void updateAccount(int i) {
System.out.println("執行了更新" + i);
}
public int deleteAccount() {
System.out.println("執行了刪除");
return 0;
}
}
4、Logger.java
public class Logger {
/**
* 用於打印日誌,計劃讓其在切入點方法執行之前執行(切入點方法即業務層方法)
*/
public void printLog() {
System.out.println("Logger類中的printLog方法開始記錄日誌了......");
}
}
5、bean.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置Spring的IoC,把accountService對象注入到容器中-->
<bean id="accountService" class="com.uos.service.impl.AccountServiceImpl"></bean>
<!--通知bean-->
<bean id="logger" class="com.uos.utils.Logger"></bean>
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的類型,並將建立通知的方法和切入點方法進行關聯-->
<aop:before method="printLog" pointcut="execution(* com.uos.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
6、AopTest.java
public class AopTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
IAccountService accountService = (IAccountService) applicationContext.getBean("accountService");
accountService.saveAccount();
}
}
7、運行結果
三、基於註解的AOP
本案例基於XML的AOP的案例進行配置。
1、添加@Service註解
2、配置切面類
@Component("logger")
@Aspect //表示當前類是一個切面類
public class Logger {
@Pointcut("execution(* com.uos.service.impl.*.*(..))")
public void pt1(){};
/**
* 前置通知
*/
//@Before("pt1()")
public void beforePrintLog() {
System.out.println("前置通知Logger類中的beforePrintLog方法開始記錄日誌了......");
}
/**
* 後置通知
*/
// @AfterReturning("pt1()")
public void afterPrintLog() {
System.out.println("後置通知Logger類中的afterPrintLog方法開始記錄日誌了......");
}
/**
* 異常通知
*/
// @AfterThrowing("pt1()")
public void throwingPrintLog() {
System.out.println("異常通知Logger類中的throwingPrintLog方法開始記錄日誌了......");
}
/**
* 最終通知
*/
// @After("pt1()")
public void finalPrintLog() {
System.out.println("最終通知Logger類中的finalPrintLog方法開始記錄日誌了......");
}
/**
* 環繞通知
*/
@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
// 得到方法執行所需的參數
Object[] args = pjp.getArgs();
System.out.println("Logger類中的aroundPrintLog方法開始記錄日誌了......前置");
// 明確調用業務層方法
rtValue= pjp.proceed(args);
System.out.println("Logger類中的aroundPrintLog方法開始記錄日誌了......後置");
return rtValue;
} catch (Throwable t) {
System.out.println("Logger類中的aroundPrintLog方法開始記錄日誌了......異常");
throw new RuntimeException(t);
} finally {
System.out.println("Logger類中的aroundPrintLog方法開始記錄日誌了......最終");
}
}
}
3、bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--告知Spring創建容器時需要掃描的包-->
<context:component-scan base-package="com.uos"></context:component-scan>
<!--配置Spring開啓註解AOP的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>