1 Spring boot擴充套件點
1。1 ApplicationContextInitializer
1。1。1 自定義介面
在ApplicationContext初始化時,呼叫refresh方法之前執行,refresh呼叫之後容器基本上初始化完成。
1。1。2 介面註冊
自定義ApplicationContextInitialier介面之後需要註冊到spring 容器中
Ø 透過ApplicationContext。addInitialier()
Ø 透過在啟動檔案中配置context。initialier。clases=xxxx方式註冊
Ø 在META-INF/spring。factories中配置org。springframework。context。 ApplicationContextInitializer=xxxx
1。2 CommandLineRunner
CommandLineRunner是在容器啟動成功後最後一次回撥。可透過@Order註解控制呼叫順序,越小越線執行,執行步驟同樣是自定義介面,註冊到spring容器。
Spring boot提供了類似功能ApplicationRunner,差別是ApplicationRunner的介面實現類引數是封裝後的。CommandLineRunner的實現引數是最原始引數
2 Spring boot AOP
本節主要講解spring boot 中AOP的使用,關於什麼是AOP,AOP的具體原理,參見spring學習中的AOP原理一節。AOP有幾個組成要數:切面、通知(前置通知、後置通知、環繞通知)、切入點,使用AOP之前需要把AOP相關的jar包引入到工程。
2。1 新增spring boot aop依賴
spring boot 為使用aop提供了一個啟動項 ,在需要使用aop工程的pom檔案中新增AOP啟動項。
我們看到spring-boot-starter-aop工程中,只是載入了spring-aop 和aspectjweaver兩個工程。從這裡也可以看出來,spring boot不是一門新的技術,而是從當一個組裝工廠。
2。2 編寫切面、通知、切入點
如下以一個統計方法執行時間的切面為例進行講解。我們首先編寫切面Aspect,切面需要納入到spring 容器中進行管理。要記錄方法執行時間,需要記錄方法執行前和執行後的時間,因此選擇環繞通知@Around。
對於環繞通知around有一個需要注意的地方,必須把返回執行結果,否則外層拿不到結果。
方法呼叫
執行結果:
2。3 Spring boot AopAutoConfiguration
Spring boot 提供了一個AopAutoConfiguration配置類,這個配置類主要用來配置AOP的代理型別。 下面我們做一個小實驗來研究AopAutoConfiguration的具體用途。
2。3。1 原始碼分析
分析原始碼發現AopAutoConfiguration提供了兩個方法,一個是配置JDK動態代理,一個是配置CGLIB代理。
根據@ConditionalOnClass,@ConditionalOnProperty兩個註解分析要啟用AopAutoConfiguration需要配置spring。aop。auto引數,預設spring。aop。auto=true。
2。3。2 連線點有介面實現
既然是配置代理型別,我們先看一下預設是否使用代理,以及使用什麼代理。
執行結果:
執行結果分析:
執行結果顯示在不配置spring。aop。auto的情況下預設是啟用AOP,並且使用的是jdk動態代理。
在application。properties中新增spring。aop。auto=true配置專案,發現結果與配有配置相同。
修改配置spring。aop。auto=false
執行結果顯示沒有執行通知方法:
修改配置項
spring。aop。auto=true
spring。aop。proxy-target-class=true
執行結果:
執行結果顯示使用的是CGLIB動態。
修改配置項
spring。aop。auto=true
spring。aop。proxy-target-class=false
執行結果:
2。3。3 連線點不使用介面
我們稍微修改一下UserDaoImpl類,把介面去掉,再看看結果
執行結果:
下面我們在application。properties配置檔案中配置spring。aop。auto、和spring。aop。proxy-target-class引數
spring。aop。auto=true
spring。aop。proxy-target-class=false
執行結果:
修改spring。aop。proxy-target-class=true,再觀察執行結果
spring。aop。auto=true
spring。aop。proxy-target-class=true
執行結果:
2。3。4 總結
a)spring。aop。auto配置項決定是否啟用aop,預設啟用
b)spring。aop。proxy-target-class配置項決定代理型別,預設spring。aop。proxy-target-class=false使用JDK動態代理,
c) spring。aop。proxy-target-class=true時使用CGLIB代理
d)連線點不使用介面時,無論spring。aop。proxy-target-class如何配置都是使用CGLIB代理