編寫基於spring註解的aop編程案例
步驟:
/**
-
@author 劉東平
-
@version 創建時間:2019年5月2日 下午7:57:21
- Aop切面註解編程【動態代理】
-
:指在程序運行之間動態的將某段代碼切入到指定方法指定位置進行運行編程方式
- 操作步驟:
- 1)、導入Aop模塊:Spring Aop的依賴(spring-aspects)
- 2)、定義一個業務邏輯類(computer),在業務邏輯運行的時候將
- 日誌打印一下(方法之前、方法之後、方法正常結束、方法拋出異常)
- 3)、定義一個日誌切面類(ComputerAspect),切面類裏面的方法需要動態的感知
- Computer.div方法運行到哪一步了。
-
通知方法:
-
前置通知:(@Before)ComputerStart,在目標方法(div)運行之前運行。
-
後置通知:(@After)ComputerEnd,在目標方法(div)運行結束之後運行
-
返回通知:(@AfterTrowing)ComputerReturn,在目標方法(div)正常返回之後運行
-
異常通知:(@AfterThrowing)ComputerException,在目標方法出現異常以後運行
-
環繞通知:動態通知,動態代理,手動推進目標方法運行(joinPoint.procced)
- 4)、給切面類的目標的方法標註何時何地運行(通知註解)
- 5)、將切面類和業務邏輯類(目標方法所在類)加入到容器當中。
- 6)、需要告訴spring那個是切面類,則需要在的切面的類添加@Aspect註解聲明一下
- 7)、【關鍵:開啓基於註解的AOP編程】需要的開啓的aop切面註解@EnableAspectJAutoProxy
- 關鍵三步:
- 1)將業務邏輯組件和切面類都加入到容器當中,並且告訴容器的那個是切面類(@Aspect)
- 2)在切面類的每一個通知方法上標註通知註解,告訴spring的何時何地運行(切入點表達式【參照spring-aop有關文檔】
- 3)開啓基於註解的aop模式,@EnableAspectProxy類
*/
主配置類
package com.ldp.Srping_Annotation.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.ldp.Srping_Annotation.aop.Computer;
import com.ldp.Srping_Annotation.aop.ComputerAspect;
@EnableAspectJAutoProxy
@Configuration
public class MyConfigOfAspects {
//將業務邏輯類添加到容器
@Bean
public Computer computer() {
return new Computer();
}
//將切面類添加到容器
@Bean
public ComputerAspect computerAspect() {
return new ComputerAspect();
}
}
業務邏輯類Computer
package com.ldp.Srping_Annotation.aop;
//需要進行的aop編程的一個業務邏輯類computer,要對div進行切面編程
public class Computer {
//除法運算
public int div(int i,int j) {
return i/j;
}
}
切面類ComputerAspect
package com.ldp.Srping_Annotation.aop;
import java.util.ArrayList;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
*
* @author 劉東平
* @version 創建時間:2019年5月2日 下午8:05:07
* 這是一個切面類:需要添加@Aspect註解告訴spring容器這是一個切面類
*/
@Aspect
public class ComputerAspect {
//抽取公共的切入點表達式
//1.本類引用
//2.其他的切面引用
@Pointcut("execution(public int com.ldp.Srping_Annotation.aop.Computer.*(..))")
public void pointCut() {};
//注意JoinPoint必須放在參數列表的第一位,否則會拋異常
@Before("pointCut()")
public void ComputerStart(JoinPoint joinPoint) {
//獲得參數列表
Object[] args = joinPoint.getArgs();
System.out.println(joinPoint.getSignature().getName()
+"運行中..@Before..參數列表{"+Arrays.asList(args)+"}");
}
@After("pointCut()")
public void ComputerEnd(JoinPoint joinPoint) {
System.out.println(joinPoint.getSignature().getName()
+"結束....@After");
}
@AfterReturning(value="pointCut()",returning="result")
public void ComputerReturn(JoinPoint joinPoint,Object result) {
System.out.println(joinPoint.getSignature().getName()
+"正常結束..@AfterReturning..返回值結果{"+result+"}");
}
@AfterThrowing(value="pointCut()",throwing="exception")
public void ComputerException(JoinPoint joinPoint,Exception exception) {
System.out.println(joinPoint.getSignature().getName()
+"出現異常..@AfterThrowing..異常信息{"+exception+"}");
}
}
測試類AspectsTest
package com.ldp.Srping_Annotation;
//這是一個測試Aop情況的測試類
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.ldp.Srping_Annotation.aop.Computer;
import com.ldp.Srping_Annotation.config.MyConfigAutowride;
import com.ldp.Srping_Annotation.config.MyConfigOfAspects;
public class AspectsTest {
private ApplicationContext applicationContext;
@Before
public void init() {
applicationContext=new AnnotationConfigApplicationContext(MyConfigOfAspects.class);
}
@Test
public void testPrintf() {
//獲取容器當中所有的id名稱
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String string : beanDefinitionNames) {
System.out.println(string);
}
}
@Test
public void TestAop() {
//注意自己創建的Computer調用是無法利用aop編程 的
//只有從容器當中獲取到對象的,才被spring管理了,纔可以進行的Soring的Aop切面編程
Computer bean = applicationContext.getBean(Computer.class);
int div = bean.div(9,3);
System.out.println("計算結果"+div);
}
}
正常測試結果:
五月 02, 2019 8:54:33 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@e73f9ac: startup date [Thu May 02 20:54:33 CST 2019]; root of context hierarchy
五月 02, 2019 8:54:34 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
div運行中..@Before..參數列表{[9, 3]}
div結束....@After
div正常結束..@AfterReturning..返回值結果{3}
計算結果3
異常測試
五月 02, 2019 9:02:38 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@e73f9ac: startup date [Thu May 02 21:02:37 CST 2019]; root of context hierarchy
五月 02, 2019 9:02:38 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
div運行中..@Before..參數列表{[9, 0]}
div結束....@After
div出現異常..@AfterThrowing..異常信息{java.lang.ArithmeticException: / by zero}
原理:
* AOP原理:【看給容器中註冊了什麼組件,這個組件什麼時候工作,這個組件的功能是什麼?】
* @EnableAspectJAutoProxy;
* 1、@EnableAspectJAutoProxy是什麼?
* @Import(AspectJAutoProxyRegistrar.class):給容器中導入AspectJAutoProxyRegistrar
* 利用AspectJAutoProxyRegistrar自定義給容器中註冊bean;BeanDefinetion
* internalAutoProxyCreator=AnnotationAwareAspectJAutoProxyCreator
*
* 給容器中註冊一個AnnotationAwareAspectJAutoProxyCreator;
*
* 2、 AnnotationAwareAspectJAutoProxyCreator:
* AnnotationAwareAspectJAutoProxyCreator
* ->AspectJAwareAdvisorAutoProxyCreator
* ->AbstractAdvisorAutoProxyCreator
* ->AbstractAutoProxyCreator
* implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
* 關注後置處理器(在bean初始化完成前後做事情)、自動裝配BeanFactory
*
* AbstractAutoProxyCreator.setBeanFactory()
* AbstractAutoProxyCreator.有後置處理器的邏輯;
*
* AbstractAdvisorAutoProxyCreator.setBeanFactory()-》initBeanFactory()
*
* AnnotationAwareAspectJAutoProxyCreator.initBeanFactory()
*
*
* 流程:
* 1)、傳入配置類,創建ioc容器
* 2)、註冊配置類,調用refresh()刷新容器;
* 3)、registerBeanPostProcessors(beanFactory);註冊bean的後置處理器來方便攔截bean的創建;
* 1)、先獲取ioc容器已經定義了的需要創建對象的所有BeanPostProcessor
* 2)、給容器中加別的BeanPostProcessor
* 3)、優先註冊實現了PriorityOrdered接口的BeanPostProcessor;
* 4)、再給容器中註冊實現了Ordered接口的BeanPostProcessor;
* 5)、註冊沒實現優先級接口的BeanPostProcessor;
* 6)、註冊BeanPostProcessor,實際上就是創建BeanPostProcessor對象,保存在容器中;
* 創建internalAutoProxyCreator的BeanPostProcessor【AnnotationAwareAspectJAutoProxyCreator】
* 1)、創建Bean的實例
* 2)、populateBean;給bean的各種屬性賦值
* 3)、initializeBean:初始化bean;
* 1)、invokeAwareMethods():處理Aware接口的方法回調
* 2)、applyBeanPostProcessorsBeforeInitialization():應用後置處理器的postProcessBeforeInitialization()
* 3)、invokeInitMethods();執行自定義的初始化方法
* 4)、applyBeanPostProcessorsAfterInitialization();執行後置處理器的postProcessAfterInitialization();
* 4)、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)創建成功;--》aspectJAdvisorsBuilder
* 7)、把BeanPostProcessor註冊到BeanFactory中;
* beanFactory.addBeanPostProcessor(postProcessor);
* =======以上是創建和註冊AnnotationAwareAspectJAutoProxyCreator的過程========
*
* AnnotationAwareAspectJAutoProxyCreator => InstantiationAwareBeanPostProcessor
* 4)、finishBeanFactoryInitialization(beanFactory);完成BeanFactory初始化工作;創建剩下的單實例bean
* 1)、遍歷獲取容器中所有的Bean,依次創建對象getBean(beanName);
* getBean->doGetBean()->getSingleton()->
* 2)、創建bean
* 【AnnotationAwareAspectJAutoProxyCreator在所有bean創建之前會有一個攔截,InstantiationAwareBeanPostProcessor,會調用postProcessBeforeInstantiation()】
* 1)、先從緩存中獲取當前bean,如果能獲取到,說明bean是之前被創建過的,直接使用,否則再創建;
* 只要創建好的Bean都會被緩存起來
* 2)、createBean();創建bean;
* AnnotationAwareAspectJAutoProxyCreator 會在任何bean創建之前先嚐試返回bean的實例
* 【BeanPostProcessor是在Bean對象創建完成初始化前後調用的】
* 【InstantiationAwareBeanPostProcessor是在創建Bean實例之前先嚐試用後置處理器返回對象的】
* 1)、resolveBeforeInstantiation(beanName, mbdToUse);解析BeforeInstantiation
* 希望後置處理器在此能返回一個代理對象;如果能返回代理對象就使用,如果不能就繼續
* 1)、後置處理器先嚐試返回對象;
* bean = applyBeanPostProcessorsBeforeInstantiation():
* 拿到所有後置處理器,如果是InstantiationAwareBeanPostProcessor;
* 就執行postProcessBeforeInstantiation
* if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
*
* 2)、doCreateBean(beanName, mbdToUse, args);真正的去創建一個bean實例;和3.6流程一樣;
* 3)、
*
*
* AnnotationAwareAspectJAutoProxyCreator【InstantiationAwareBeanPostProcessor】 的作用:
* 1)、每一個bean創建之前,調用postProcessBeforeInstantiation();
* 關心MathCalculator和LogAspect的創建
* 1)、判斷當前bean是否在advisedBeans中(保存了所有需要增強bean)
* 2)、判斷當前bean是否是基礎類型的Advice、Pointcut、Advisor、AopInfrastructureBean,
* 或者是否是切面(@Aspect)
* 3)、是否需要跳過
* 1)、獲取候選的增強器(切面裏面的通知方法)【List<Advisor> candidateAdvisors】
* 每一個封裝的通知方法的增強器是 InstantiationModelAwarePointcutAdvisor;
* 判斷每一個增強器是否是 AspectJPointcutAdvisor 類型的;返回true
* 2)、永遠返回false
*
* 2)、創建對象
* postProcessAfterInitialization;
* return wrapIfNecessary(bean, beanName, cacheKey);//包裝如果需要的情況下
* 1)、獲取當前bean的所有增強器(通知方法) Object[] specificInterceptors
* 1、找到候選的所有的增強器(找哪些通知方法是需要切入當前bean方法的)
* 2、獲取到能在bean使用的增強器。
* 3、給增強器排序
* 2)、保存當前bean在advisedBeans中;
* 3)、如果當前bean需要增強,創建當前bean的代理對象;
* 1)、獲取所有增強器(通知方法)
* 2)、保存到proxyFactory
* 3)、創建代理對象:Spring自動決定
* JdkDynamicAopProxy(config);jdk動態代理;
* ObjenesisCglibAopProxy(config);cglib的動態代理;
* 4)、給容器中返回當前組件使用cglib增強了的代理對象;
* 5)、以後容器中獲取到的就是這個組件的代理對象,執行目標方法的時候,代理對象就會執行通知方法的流程;
*
*
* 3)、目標方法執行 ;
* 容器中保存了組件的代理對象(cglib增強後的對象),這個對象裏面保存了詳細信息(比如增強器,目標對象,xxx);
* 1)、CglibAopProxy.intercept();攔截目標方法的執行
* 2)、根據ProxyFactory對象獲取將要執行的目標方法攔截器鏈;
* List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
* 1)、List<Object> interceptorList保存所有攔截器 5
* 一個默認的ExposeInvocationInterceptor 和 4個增強器;
* 2)、遍歷所有的增強器,將其轉爲Interceptor;
* registry.getInterceptors(advisor);
* 3)、將增強器轉爲List<MethodInterceptor>;
* 如果是MethodInterceptor,直接加入到集合中
* 如果不是,使用AdvisorAdapter將增強器轉爲MethodInterceptor;
* 轉換完成返回MethodInterceptor數組;
*
* 3)、如果沒有攔截器鏈,直接執行目標方法;
* 攔截器鏈(每一個通知方法又被包裝爲方法攔截器,利用MethodInterceptor機制)
* 4)、如果有攔截器鏈,把需要執行的目標對象,目標方法,
* 攔截器鏈等信息傳入創建一個 CglibMethodInvocation 對象,
* 並調用 Object retVal = mi.proceed();
* 5)、攔截器鏈的觸發過程;
* 1)、如果沒有攔截器執行執行目標方法,或者攔截器的索引和攔截器數組-1大小一樣(指定到了最後一個攔截器)執行目標方法;
* 2)、鏈式獲取每一個攔截器,攔截器執行invoke方法,每一個攔截器等待下一個攔截器執行完成返回以後再來執行;
* 攔截器鏈的機制,保證通知方法與目標方法的執行順序;
*
* 總結:
* 1)、 @EnableAspectJAutoProxy 開啓AOP功能
* 2)、 @EnableAspectJAutoProxy 會給容器中註冊一個組件 AnnotationAwareAspectJAutoProxyCreator
* 3)、AnnotationAwareAspectJAutoProxyCreator是一個後置處理器;
* 4)、容器的創建流程:
* 1)、registerBeanPostProcessors()註冊後置處理器;創建AnnotationAwareAspectJAutoProxyCreator對象
* 2)、finishBeanFactoryInitialization()初始化剩下的單實例bean
* 1)、創建業務邏輯組件和切面組件
* 2)、AnnotationAwareAspectJAutoProxyCreator攔截組件的創建過程
* 3)、組件創建完之後,判斷組件是否需要增強
* 是:切面的通知方法,包裝成增強器(Advisor);給業務邏輯組件創建一個代理對象(cglib);
* 5)、執行目標方法:
* 1)、代理對象執行目標方法
* 2)、CglibAopProxy.intercept();
* 1)、得到目標方法的攔截器鏈(增強器包裝成攔截器MethodInterceptor)
* 2)、利用攔截器的鏈式機制,依次進入每一個攔截器進行執行;
* 3)、效果:
* 正常執行:前置通知-》目標方法-》後置通知-》返回通知
* 出現異常:前置通知-》目標方法-》後置通知-》異常通知
*
*
*
*/