我們一起了解 Spring 中的 AOP !
本文轉載自微信公眾號「程序員千羽」,作者程序員千羽 。轉載本文請聯系程序員千羽公眾號。
- 1. Spring AOP簡介
- 2. 動態代理
- jdk動態代理
- CGLIB代理
- 3. 基于代理類的AOP實現
- Spring的通知類型
- ProxyFactoryBean
- 4. AspectJ開發
- 基于XML的聲明式AspectJ
- 基于注解的聲明式AspectJ(常用)
“GitHub:https://github.com/nateshao/ssm/tree/master/103-spring-aop
1. Spring AOP簡介
什么是AOP?
AOP的全稱是Aspect-Oriented Programming,即面向切面編程(也稱面向方面編程)。它是面向對象編程(OOP)的一種補充,目前已成為一種比較成熟的編程方式。
在傳統的業務處理代碼中,通常都會進行事務處理、日志記錄等操作。雖然使用OOP可以通過組合或者繼承的方式來達到代碼的重用,但如果要實現某個功能(如日志記錄),同樣的代碼仍然會分散到各個方法中。這樣,如果想要關閉某個功能,或者對其進行修改,就必須要修改所有的相關方法。這不但增加了開發人員的工作量,而且提高了代碼的出錯率。
為了解決這一問題,AOP思想隨之產生。AOP采取橫向抽取機制,將分散在各個方法中的重復代碼提取出來,然后在程序編譯或運行時,再將這些提取出來的代碼應用到需要執行的地方。這種采用橫向抽取機制的方式,采用傳統的OOP思想顯然是無法辦到的,因為OOP只能實現父子關系的縱向的重用。雖然AOP是一種新的編程思想,但卻不是OOP的替代品,它只是OOP的延伸和補充。
類與切面的關系
AOP的使用,使開發人員在編寫業務邏輯時可以專心于核心業務,而不用過多的關注于其他業務邏輯的實現,這不但提高了開發效率,而且增強了代碼的可維護性。
Proxy(代理):將通知應用到目標對象之后,被動態創建的對象。
Weaving(織入):將切面代碼插入到目標對象上,從而生成代理對象的過程。
2. 動態代理
jdk動態代理
“JDK動態代理是通過java.lang.reflect.Proxy 類來實現的,我們可以調用Proxy類的newProxyInstance()方法來創建代理對象。對于使用業務接口的類,Spring默認會使用JDK動態代理來實現AOP。
UserDao.java
- public interface UserDao {
- public void addUser();
- public void deleteUser();
- }
UserDaoImpl.java
- package com.nateshao.aop;
- import org.springframework.stereotype.Repository;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 17:59
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- @Repository("userDao")
- public class UserDaoImpl implements UserDao{
- @Override
- public void addUser() {
- System.out.println("添加用戶");
- }
- @Override
- public void deleteUser() {
- System.out.println("刪除用戶");
- }
- }
JdkProxy.java
- package com.nateshao.aop;
- import com.nateshao.aspect.MyAspect;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 18:01
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description: JDK代理類
- */
- public class JdkProxy implements InvocationHandler {
- // 聲明目標類接口
- private UserDao userDao;
- // 創建代理方法
- public Object createProxy(UserDao userDao) {
- this.userDao = userDao;
- // 1.類加載器
- ClassLoader classLoader = JdkProxy.class.getClassLoader();
- // 2.被代理對象實現的所有接口
- Class[] clazz = userDao.getClass().getInterfaces();
- // 3.使用代理類,進行增強,返回的是代理后的對象
- return Proxy.newProxyInstance(classLoader,clazz,this);
- }
- /**
- * 所有動態代理類的方法調用,都會交由invoke()方法去處理
- * @param proxy 被代理后的對象
- * @param method 將要被執行的方法信息(反射)
- * @param args 執行方法時需要的參數
- * @return
- * @throws Throwable
- */
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- // 聲明切面
- MyAspect myAspect = new MyAspect();
- // 前增強
- myAspect.check_Permissions();
- // 在目標類上調用方法,并傳入參數
- Object obj = method.invoke(userDao, args);
- // 后增強
- myAspect.log();
- return obj;
- }
- }
CGLIB代理
通過前面的學習可知,JDK的動態代理用起來非常簡單,但它是有局限性的,使用動態代理的對象必須實現一個或多個接口。
如果想代理沒有實現接口的類,那么可以使用CGLIB代理。
“CGLIB(Code Generation Library)是一個高性能開源的代碼生成包,它采用非常底層的字節碼技術,對指定的目標類生成一個子類,并對子類進行增強。
UserDao.java
- public class UserDao {
- public void addUser(){
- System.out.println("添加用戶");
- }
- public void deleteUser(){
- System.out.println("添加用戶");
- }
- }
CglibProxy.java
- package com.nateshao.cglib;
- import com.nateshao.aspect.MyAspect;
- import org.springframework.cglib.proxy.Enhancer;
- import org.springframework.cglib.proxy.MethodInterceptor;
- import org.springframework.cglib.proxy.MethodProxy;
- import java.lang.reflect.Method;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 18:18
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- // 代理類
- public class CglibProxy implements MethodInterceptor {
- // 代理方法
- public Object createProxy(Object target) {
- // 創建一個動態類對象
- Enhancer enhancer = new Enhancer();
- // 確定需要增強的類,設置其父類
- enhancer.setSuperclass(target.getClass());
- // 添加回調函數
- enhancer.setCallback(this);
- // 返回創建的代理類
- return enhancer.create();
- }
- /**
- * @param proxy CGlib根據指定父類生成的代理對象
- * @param method 攔截的方法
- * @param args 攔截方法的參數數組
- * @param methodProxy 方法的代理對象,用于執行父類的方法
- * @return
- * @throws Throwable
- */
- @Override
- public Object intercept(Object proxy, Method method, Object[] args,
- MethodProxy methodProxy) throws Throwable {
- // 創建切面類對象
- MyAspect myAspect = new MyAspect();
- // 前增強
- myAspect.check_Permissions();
- // 目標方法執行
- Object obj = methodProxy.invokeSuper(proxy, args);
- // 后增強
- myAspect.log();
- return obj;
- }
- }
CglibTest.java
- package com.nateshao.cglib;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 18:25
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- public class CglibTest {
- public static void main(String[] args) {
- // 創建代理對象
- CglibProxy cglibProxy = new CglibProxy();
- // 創建目標對象
- UserDao userDao = new UserDao();
- // 獲取增強后的目標對象
- UserDao userDao1 = (UserDao)cglibProxy.createProxy(userDao);
- // 執行方法
- userDao1.addUser();
- userDao1.deleteUser();
- }
- }
3. 基于代理類的AOP實現
Spring的通知類型
Spring按照通知在目標類方法的連接點位置,可以分為5種類型,具體如下:
- org.springframework.aop.MethodBeforeAdvice(前置通知)
在目標方法執行前實施增強,可以應用于權限管理等功能。
- org.springframework.aop.AfterReturningAdvice(后置通知)
在目標方法執行后實施增強,可以應用于關閉流、上傳文件、刪除臨時文件等功能。
- org.aopalliance.intercept.MethodInterceptor(環繞通知)
在目標方法執行前后實施增強,可以應用于日志、事務管理等功能。
- org.springframework.aop.ThrowsAdvice(異常拋出通知)
在方法拋出異常后實施增強,可以應用于處理異常記錄日志等功能。
- org.springframework.aop.IntroductionInterceptor(引介通知)
在目標類中添加一些新的方法和屬性,可以應用于修改老版本程序。
ProxyFactoryBean
“ProxyFactoryBean是FactoryBean接口的實現類,FactoryBean負責實例化一個Bean,而ProxyFactoryBean負責為其他Bean創建代理實例。在Spring中,使用ProxyFactoryBean是創建AOP代理的基本方式。
ProxyFactoryBean類中的常用可配置屬性如下:
代碼實現
MyAspect.java
- package com.nateshao.factorybean;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 18:36
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description: 切面類
- */
- public class MyAspect implements MethodInterceptor {
- @Override
- public Object invoke(MethodInvocation mi) throws Throwable {
- check_Permissions();
- // 執行目標方法
- Object obj = mi.proceed();
- log();
- return obj;
- }
- public void check_Permissions(){
- System.out.println("模擬檢查權限...");
- }
- public void log(){
- System.out.println("模擬記錄日志...");
- }
- }
applicationContext.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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
- <!-- 1 目標類 -->
- <bean id="userDao" class="com.nateshao.jdk.UserDaoImpl" />
- <!-- 2 切面類 -->
- <bean id="myAspect" class="com.nateshao.factorybean.MyAspect" />
- <!-- 3 使用Spring代理工廠定義一個名稱為userDaoProxy的代理對象 -->
- <bean id="userDaoProxy"
- class="org.springframework.aop.framework.ProxyFactoryBean">
- <!-- 3.1 指定代理實現的接口-->
- <property name="proxyInterfaces"
- value="com.nateshao.jdk.UserDao" />
- <!-- 3.2 指定目標對象 -->
- <property name="target" ref="userDao" />
- <!-- 3.3 指定切面,織入環繞通知 -->
- <property name="interceptorNames" value="myAspect" />
- <!-- 3.4 指定代理方式,true:使用cglib,false(默認):使用jdk動態代理 -->
- <property name="proxyTargetClass" value="true" />
- </bean>
- </beans>
ProxyFactoryBeanTest.java
- package com.nateshao.factorybean;
- import com.nateshao.jdk.UserDao;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 18:41
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description: 測試類
- */
- public class ProxyFactoryBeanTest {
- public static void main(String args[]) {
- String xmlPath = "applicationContext.xml";
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
- // 從Spring容器獲得內容
- UserDao userDao = (UserDao) applicationContext.getBean("userDaoProxy");
- // 執行方法
- userDao.addUser();
- userDao.deleteUser();
- }
- }
4. AspectJ開發
“概述:AspectJ是一個基于Java語言的AOP框架,它提供了強大的AOP功能。Spring 2.0以后,Spring AOP引入了對AspectJ的支持,并允許直接使用AspectJ進行編程,而Spring自身的AOP API也盡量與AspectJ保持一致。新版本的Spring框架,也建議使用AspectJ來開發AOP。使用AspectJ實現AOP有兩種方式:一種是基于XML的聲明式AspectJ,另一種是基于注解的聲明式AspectJ。
基于XML的聲明式AspectJ
“基于XML的聲明式AspectJ是指通過XML文件來定義切面、切入點及通知,所有的切面、切入點和通知都必須定義在< aop:config >元素內。
< aop:config >元素及其子元素如下:
小提示:圖中灰色部分標注的元素即為常用的配置元素
XML文件中常用元素的配置方式如下:
- <bean id="myAspect" class="com.nateshao.aspectj.xml.MyAspect" />
- <aop:config>
- <aop:aspect id="aspect" ref="myAspect">
- <aop:pointcut expression="execution(* com.nateshao.jdk.*.*(..))“ id="myPointCut" />
- <aop:before method="myBefore" pointcut-ref="myPointCut" />
- <aop:after-returning method="myAfterReturning“ pointcut-ref="myPointCut" returning="returnVal" />
- <aop:around method="myAround" pointcut-ref="myPointCut" />
- <aop:after-throwing method="myAfterThrowing“ pointcut-ref="myPointCut" throwing="e" />
- <aop:after method="myAfter" pointcut-ref="myPointCut" />
- </aop:aspect>
- </aop:config>
配置切面
“在Spring的配置文件中,配置切面使用的是< aop:aspect >元素,該元素會將一個已定義好的Spring Bean轉換成切面Bean,所以要在配置文件中先定義一個普通的Spring Bean。
配置< aop:aspect >元素時,通常會指定id和ref兩個屬性。
id:用于定義該切面的唯一標識名稱。 ref:用于引用普通的Spring Bean
配置切入點
“當< aop:pointcut>元素作為< aop:config>元素的子元素定義時,表示該切入點是全局切入點,它可被多個切面所共享;當< aop:pointcut>元素作為< aop:aspect>元素的子元素時,表示該切入點只對當前切面有效。
在定義< aop:pointcut>元素時,通常會指定id和expression兩個屬性。
id:用于指定切入點的唯-標識名稱。. expressione:用于指定切入點關聯的切入點表達式
切入點表達式
- execution(* com.nateshao.jdk. * . * (..)) 是定義的切入點表達式,該切入點表達式的意思是匹配com.nateshao.jdk包中任意類的任意方法的執行。
- execution(* com.nateshao.jdk..(..)) :表達式的主體
- execution(* :* 表示所有返回類型
- com.nateshao.jdk:需要攔截的包名字
- execution(* com.nateshao.jdk. * :* 代表所有類
- execution(* com.nateshao.jdk. * . * :方法名,使用* 代表所有方法
- execution(* com.nateshao.jdk..(..)) :. . 表示任意參數
配置通知
“使用< aop:aspect>的子元素可以配置5種常用通知,這5個子元素不支持使用子元素,但在使用時可以指定一些屬性,其常用屬性及其描述如下:
MyAspect.java
- package com.nateshao.aspectj.xml;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 19:56
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description: 切面類,在此類中編寫通知
- */
- public class MyAspect {
- // 前置通知
- public void myBefore(JoinPoint joinPoint) {
- System.out.print("前置通知 :模擬執行權限檢查...,");
- System.out.print("目標類是:"+joinPoint.getTarget() );
- System.out.println(",被織入增強處理的目標方法為:"
- +joinPoint.getSignature().getName());
- }
- // 后置通知
- public void myAfterReturning(JoinPoint joinPoint) {
- System.out.print("后置通知:模擬記錄日志...," );
- System.out.println("被織入增強處理的目標方法為:"
- + joinPoint.getSignature().getName());
- }
- /**
- * 環繞通知
- * ProceedingJoinPoint 是JoinPoint子接口,表示可以執行目標方法
- * 1.必須是Object類型的返回值
- * 2.必須接收一個參數,類型為ProceedingJoinPoint
- * 3.必須throws Throwable
- */
- public Object myAround(ProceedingJoinPoint proceedingJoinPoint)
- throws Throwable {
- // 開始
- System.out.println("環繞開始:執行目標方法之前,模擬開啟事務...");
- // 執行當前目標方法
- Object obj = proceedingJoinPoint.proceed();
- // 結束
- System.out.println("環繞結束:執行目標方法之后,模擬關閉事務...");
- return obj;
- }
- // 異常通知
- public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
- System.out.println("異常通知:" + "出錯了" + e.getMessage());
- }
- // 最終通知
- public void myAfter() {
- System.out.println("最終通知:模擬方法結束后的釋放資源...");
- }
- }
config.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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
- <!-- 1 目標類 -->
- <bean id="userDao" class="com.nateshao.jdk.UserDaoImpl" />
- <!-- 2 切面類 -->
- <bean id="myAspect" class="com.nateshao.factorybean.MyAspect" />
- <!-- 3 使用Spring代理工廠定義一個名稱為userDaoProxy的代理對象 -->
- <bean id="userDaoProxy"
- class="org.springframework.aop.framework.ProxyFactoryBean">
- <!-- 3.1 指定代理實現的接口-->
- <property name="proxyInterfaces"
- value="com.nateshao.jdk.UserDao" />
- <!-- 3.2 指定目標對象 -->
- <property name="target" ref="userDao" />
- <!-- 3.3 指定切面,織入環繞通知 -->
- <property name="interceptorNames" value="myAspect" />
- <!-- 3.4 指定代理方式,true:使用cglib,false(默認):使用jdk動態代理 -->
- <property name="proxyTargetClass" value="true" />
- </bean>
- </beans>
TestXmlAspectj.java
- package com.nateshao.aspectj.xml;
- import com.nateshao.jdk.UserDao;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 19:58
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- public class TestXmlAspectj {
- public static void main(String args[]) {
- String xmlPath =
- "config.xml";
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext(xmlPath);
- // 1 從spring容器獲得內容
- UserDao userDao = (UserDao) applicationContext.getBean("userDao");
- // 2 執行方法
- userDao.addUser();
- }
- }
基于注解的聲明式AspectJ(常用)
AspectJ框架為AOP的實現提供了一套注解,用以取代Spring配置文件中為實現AOP功能所配置的臃腫代碼。AspectJ的注解及其描述如下所示:
MyAspect.java
- package com.nateshao.aspectj.annotation;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.*;
- import org.springframework.stereotype.Component;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 20:06
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description: 切面類,在此類中編寫通知
- */
- @Aspect
- @Component
- public class MyAspect {
- // 定義切入點表達式
- @Pointcut("execution(* com.nateshao.jdk.*.*(..))")
- // 使用一個返回值為void、方法體為空的方法來命名切入點
- private void myPointCut(){}
- // 前置通知
- @Before("myPointCut()")
- public void myBefore(JoinPoint joinPoint) {
- System.out.print("前置通知 :模擬執行權限檢查...,");
- System.out.print("目標類是:"+joinPoint.getTarget() );
- System.out.println(",被織入增強處理的目標方法為:"
- +joinPoint.getSignature().getName());
- }
- // 后置通知
- @AfterReturning(value="myPointCut()")
- public void myAfterReturning(JoinPoint joinPoint) {
- System.out.print("后置通知:模擬記錄日志...," );
- System.out.println("被織入增強處理的目標方法為:"
- + joinPoint.getSignature().getName());
- }
- // 環繞通知
- @Around("myPointCut()")
- public Object myAround(ProceedingJoinPoint proceedingJoinPoint)
- throws Throwable {
- // 開始
- System.out.println("環繞開始:執行目標方法之前,模擬開啟事務...");
- // 執行當前目標方法
- Object obj = proceedingJoinPoint.proceed();
- // 結束
- System.out.println("環繞結束:執行目標方法之后,模擬關閉事務...");
- return obj;
- }
- // 異常通知
- @AfterThrowing(value="myPointCut()",throwing="e")
- public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
- System.out.println("異常通知:" + "出錯了" + e.getMessage());
- }
- // 最終通知
- @After("myPointCut()")
- public void myAfter() {
- System.out.println("最終通知:模擬方法結束后的釋放資源...");
- }
- }
annotation.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-4.3.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.3.xsd">
- <!-- 指定需要掃描的包,使注解生效 -->
- <context:component-scan base-package="com.nateshao" />
- <!-- 啟動基于注解的聲明式AspectJ支持 -->
- <aop:aspectj-autoproxy />
- </beans>
TestAnnotationAspectj.java
- package com.nateshao.aspectj.annotation;
- import com.nateshao.jdk.UserDao;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @date Created by 邵桐杰 on 2021/10/14 20:09
- * @微信公眾號 程序員千羽
- * @個人網站 www.nateshao.cn
- * @博客 https://nateshao.gitee.io
- * @GitHub https://github.com/nateshao
- * @Gitee https://gitee.com/nateshao
- * Description:
- */
- public class TestAnnotationAspectj {
- public static void main(String args[]) {
- String xmlPath = "annotation.xml";
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
- // 1 從spring容器獲得內容
- UserDao userDao = (UserDao) applicationContext.getBean("userDao");
- // 2 執行方法
- userDao.addUser();
- }
- }
總結
這篇文章主要講解了Spring框架中AOP的相關知識。
- 首先對AOP進行了簡單的介紹,
- 然后講解了Spring中的兩種動態代理,
- 接下來講解了Spring中基于代理類的AOP實現,
- 最后講解了如何使用AspectJ框架來進行AOP開發。
通過本章的學習,我們可以了解AOP的概念和作用,理解AOP中的相關常用術語,熟悉Spring中兩種動態代理方式的區別,并能夠掌握基于代理類和AspectJ框架的AOP開發方式。