AOP概念:
①面向切面(方面)程式設計,擴充功能不修改源代碼實作
②采取橫向抽取機制,取代了傳統縱向繼承體系重複性代碼
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuUGMiRWNjJTY2EmN3MDN0IDO5QDNjN2YykTOhFjYlJjZfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
1.png
2.png
AOP操作術語:
Joinpoint(連接配接點):類裡面可以被增強的方法
Pointcut(切入點):指要對哪些Joinpoint進行攔截的定義
Advice(通知/增強):指攔截到Joinpoint之後所要做的事情。通知分為前置通知,後置通知,異常通知,最終通知,環繞通知
Aspect(切面):是切入點和通知(引介)的結合。
3.png
spring進行AOP操作
在spring中進行aop操作,使用aspectj實作(需在官網下載下傳aspectj所需jar包。)
aspectj不是spring的一部分,和spring一起使用進行aop操作
使用aspectj實作aop的方式
基于aspectj的xml配置
- 導包
spring-aop-5.0.6.RELEASE.jar
aspectjweaver.jar
spring-aspects-5.0.6.RELEASE.jar
- 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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
使用表達式配置切入點
常用的表達式:
execution(<通路修飾符>?<傳回類型><方法名>(<參數>)<異常>)
execution(* cn.itcast.aop.Book.add(..))
execution(* cn.itcast.aop.Book.*(..))
execution(* *.*(..))
execution(* save*(..))//比對所有save開頭的方法
- Book.java
package cn.itcast.aop;
public class Book {
public void add() {
System.out.println("add.........");
}
}
- MyBook.java
package cn.itcast.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyBook {
public void before1() {
System.out.println("前置增強.........");
}
public void after1() {
System.out.println("後置增強.........");
}
public void around1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("方法之前.........");
proceedingJoinPoint.proceed();
System.out.println("方法之後.........");
}
}
- xml檔案使用
<bean id="book" class="cn.itcast.aop.Book"></bean>
<bean id="myBook" class="cn.itcast.aop.MyBook"></bean>
<aop:config>
<aop:pointcut expression="execution(* cn.itcast.aop.Book.*(..))" id="pointcut1"/>
<aop:aspect ref="myBook">
<aop:before method="before1" pointcut-ref="pointcut1"/>
<aop:after-returning method="after1" pointcut-ref="pointcut1"/>
<aop:around method="around1" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
- test測試檔案
@Test
public void testUser() {
ApplicationContext context= new ClassPathXmlApplicationContext("bean2.xml");
Book book=(Book) context.getBean("book");
book.add();
}
運作下,得到