Java Agent(上)

1、java agent是什麼?

—》對用戶透明,不侵入用戶業務代碼。讓java虛擬機加載agent jar

2、java agent有什麼用?

—>應用場景例如:調用鏈追蹤項目,在用戶無感知的情況下,記錄日誌。目前業內使用該技術的有,SkyWalking,Pinpoint(這個監控的粒度更小)

-各個 Java IDE 的調試功能,例如 eclipse、IntelliJ ;

-熱部署功能,例如 JRebel、XRebel、 spring-loaded;

-各種線上診斷工具,例如 Btrace、Greys,還有阿里的 Arthas;

-各種性能分析工具,例如 Visual VM、JConsole 等

3、java agent的實現原理?

https://zhuanlan.zhihu.com/p/147375268

4、 入門案例

4.1、 如何製造自己第一個java agent jar包

4.1.1、 第一步:我們需要一個插件來幫助我們生成帶特定格式的MAINIFEST.MF的jar

4.1.2、 第二步:在啟動項目的時候,在jvm參數中添加 -javaagent: *\ving-agent-0.0.1-SNAPSHOT.jar (在jvm上先加載agent包)

(偷偷地問)特定格式的MAINIFEST.MF是怎樣的?需要包括下面的內容

Manifest-Version: 1.0
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Premain-Class: cn.think.in.java.clazz.loader.asm.agent.PreMainTraceAgent

(再偷偷地問),難度每次都讓我手動去弄這個文件,我覺得很麻煩呀,有沒一個工具能幫我們將agent項目打包成包含MAINIFEST.MF的jar?
—–》對,你猜對了,真的有這個工具。那就是maven插件。(說到打包,肯定要想到maven或者gradle了吧)

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Project-name>${project.name}</Project-name>
                            <Project-version>${project.version}</Project-version>
                            <Premain-Class>com.tuling.agent.Agent</Premain-Class>
                            <Can-Redefine-Classes>true</Can-Redefine-Classes>
                            <Can-Retransform-Classes>true</Can-Retransform-Classes>
                            <Boot-Class-Path>javassist-3.18.1-GA.jar</Boot-Class-Path>
                        </manifestEntries>
                    </archive>
                    <skip>true</skip>
                </configuration>
            </plugin>

插件

打包之後

測試

問題二:如果有一個類已經被虛擬機加載了,那麼我們的agent包裏面的邏輯就不能加載這個類。但是我就是想把這類替換掉,怎麼辦呢?(熱更新,虛擬機不停的情況下,替換成用戶最新的代碼)

插件

agent代碼的修改

重新打包

測試

問題三:
當JVM已裝置某個類,但是我們想重新走一次premain方法,我們怎樣做呢?
插件

修改agent代碼

打包

測試

思考

看到這裏,細心的朋友,可能會帶有疑問,我在實踐的時候,發現這個類的字節碼的生成並不簡單,如果讓我自己去手動去生成那就很麻煩呀?(麻煩–》複雜度高—》容易出錯—-》上線容易出問題—》那就直接不考慮該技術)
—-》為了解決這個問題,java-ssist就出現了。關於java-ssist,請點擊。

https://www.cnblogs.com/vingLiu/p/13193517.html

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※超省錢租車方案

助力新能源車 意法半導體推新款車規碳化矽二極體

意法半導體推出新款車規碳化矽(SiC)二極體,以滿足電動汽車和插電式混合動力車(PHEVs,Plug-in Hybrids)等新能源汽車對車載充電器(OBCs,on-board battery chargers)在有限空間內處理大功率的苛刻要求。  

  新款二極體採用先進的技術可防止高電流突波燒毀裝置,其過電流保護是額定電流的2.5倍,因此設計人員可選用更小、更經濟實惠且可靠性和效能都不會受到影響的電流更小的二極體。此新碳化矽二極體通過車規產品測試,反向擊穿電壓提高到650V,能滿足設計人員和汽車廠商欲降低電壓補償係數的要求,以確保車載充電半導體元件的標準與瞬間峰值電壓之間有充足的安全邊際。   這次推出的650V二極體包括TO-220AC功率封裝的10A STPSC10H065DY和TO-220AC封裝的12A STPSC12H065DY。此外,TO-220AB封裝的STPSC20H065CTY和TO-247封裝的STPSC20H065CWY是內建2個10A二極體的雙二極體(dual-diode )產品,可最大幅度地提升空間利用度並減少車載充電器的重量。

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家公司費用,距離,噸數怎麼算?達人教你簡易估價知識!

※教你寫出一流的銷售文案?

※超省錢租車方案

擴大電動車布局 鴻海入股中國和諧汽車

鴻海於 12 月 22 日公告,以台幣約 24.84 億元入股中國和諧汽車(China Harmony Auto Holding Limited),取得 10.526% 的持股,未來雙方將展開新能源、電動車的通路合作。   和諧汽車為中國進口高級品牌汽車的第二大經銷商,擁有 25 個銷售據點,旗下代理品牌超過 10 個,包括寶馬、勞斯萊斯,MINI、奧迪、法拉利、瑪莎拉蒂等等。   而鴻海集團近來在電動車市場投資與布局也動作頻頻,鴻海集團總裁郭台銘 12 月初率領近 20 人的專家團隊,前往河南首三門峽市的速達電動汽車公司進行實地考察,並駕駛了速達電動車,正式開啟了合作契機。緊接著,富士康與北汽合資電動車租賃公司也傳出獲得中國科技局採用的好消息,成功打入當地電動車租賃市場。   這次,由鴻海主動發布重大訊息,代子公司 Foxconn (Far East) Limited 公告為了與目標公司合作發展新事業,將投資和諧汽車,以港幣約 6.09 億元(約台幣 24.84 億元),每股港幣 4.73 元,取得和諧汽車股份,持股比例將達到 10.526%。   (照片來源:)

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家公司費用,距離,噸數怎麼算?達人教你簡易估價知識!

※教你寫出一流的銷售文案?

※超省錢租車方案

特斯拉經典跑車 Roadster 推升級版 續航力達 644 公里

  美國豪華電動車商特斯拉 (Tesla) 的經典跑車「Roadster」,將推出強悍升級版!「 Roadster 3.0」充電一次可行駛 400 英哩 ( 644 公里),CNET 稱,續航力擊敗市面上所有電動車。   特斯拉執行長馬斯克 (Elon Musk) 26 日在推特宣布,新款 Roadster 可從洛杉磯一路開到舊金山,里程數將近 400 英哩,續航力無人能及,舊款 Roadster 僅能行駛 244 英哩,特斯拉熱銷的 Model S 也只有 265 英哩。   特斯拉表示,續航里程大增主要因為電池效能增加 31%,由 53kWh 增至 70kWh;新空氣力學設計減少汽車 15% 阻力;升級版的輪胎和軸承也降低 20% 的滾動阻力。   特斯拉 26 日股價漲 2.50%,收在 227.82 美元,但仍與 9 月 4 日歷史收盤新高的 286.04 美元相比,重挫了20%。     (圖片為特斯拉 Roadster 2.5,來源:)

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

※教你寫出一流的銷售文案?

※超省錢租車方案

北京2014年度剩餘新能源車指標將不再併入明年

12月25日,北京本年度最後一次小客車購車搖號舉行,227萬申請者爭奪普通小客車指標,基礎中簽比達到151∶1。新能源車指標綽綽有餘,無需搖號。

經市公安交通管理局審核確認,2014年4月26日中簽過期未用個人普通小客車配置指標734個,按規定納入本期個人普通小客車指標配置,因此本期將隨機搖出個人普通小客車指標19804個;搖出單位普通小客車指標1300個。2014年4月26日中簽過期未用個人示範應用新能源小客車配置指標1618個,2014年第5期未配置的個人示範應用新能源小客車指標869個,按規定納入本期個人范應用新能源小客車指標配置,因此本期將配置個人示範應用新能源小客車指標4157個;2014年第5期未配置的單位示範應用新能源小客車指標2646個,按規定納入本期單位示範應用新能源小客車指標配置,因此本期將配置單位示範應用新能源小客車指標4316個。因本期個人和單位示範應用新能源小客車指標申請數均小於本期指標配額,無需搖號,直接配置。

不過按照規定,本期剩餘的新能源車指標將不再併入下一年。

根據北京市去年底發佈的《北京市2013—2017年機動車排放污染控制工作方案》任務分解表,2015至2017年,每年共將配置機動車指標15萬個,但普通小客車指標將逐年縮水。2014年普通小客車指標13萬個、示範應用新能源小客車指標2萬個,2015年普通小客車指標將縮1萬個至12萬個,新能源車指標將增加1萬個至3萬個,新能源車的中簽幾率將進一步增加。2016年和2017年,普通車指標和新能源車指標將分別調整為9萬個和6萬個。

本站聲明:網站內容來源於EnergyTrend https://www.energytrend.com.tw/ev/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※超省錢租車方案

Java是如何實現Future模式的?萬字詳解!

JDK1.8源碼分析項目(中文註釋)Github地址:

https://github.com/yuanmabiji/jdk1.8-sourcecode-blogs

1 Future是什麼?

先舉個例子,我們平時網購買東西,下單後會生成一個訂單號,然後商家會根據這個訂單號發貨,發貨后又有一個快遞單號,然後快遞公司就會根據這個快遞單號將網購東西快遞給我們。在這一過程中,這一系列的單號都是我們收貨的重要憑證。

因此,JDK的Future就類似於我們網購買東西的單號,當我們執行某一耗時的任務時,我們可以另起一個線程異步去執行這個耗時的任務,同時我們可以干點其他事情。當事情幹完后我們再根據future這個”單號”去提取耗時任務的執行結果即可。因此Future也是多線程中的一種應用模式。

擴展: 說起多線程,那麼Future又與Thread有什麼區別呢?最重要的區別就是Thread是沒有返回結果的,而Future模式是有返回結果的。

2 如何使用Future

前面搞明白了什麼是Future,下面我們再來舉個簡單的例子看看如何使用Future。

假如現在我們要打火鍋,首先我們要準備兩樣東西:把水燒開和準備食材。因為燒開水是一個比較漫長的過程(相當於耗時的業務邏輯),因此我們可以一邊燒開水(相當於另起一個線程),一邊準備火鍋食材(主線程),等兩者都準備好了我們就可以開始打火鍋了。

// DaHuoGuo.java

public class DaHuoGuo {
	public static void main(String[] args) throws Exception {
		FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				System.out.println(Thread.currentThread().getName() + ":" + "開始燒開水...");
				// 模擬燒開水耗時
				Thread.sleep(2000);
				System.out.println(Thread.currentThread().getName() + ":"  + "開水已經燒好了...");
				return "開水";
			}
		});

		Thread thread = new Thread(futureTask);
		thread.start();

		// do other thing
		System.out.println(Thread.currentThread().getName() + ":"  + " 此時開啟了一個線程執行future的邏輯(燒開水),此時我們可以干點別的事情(比如準備火鍋食材)...");
		// 模擬準備火鍋食材耗時
		Thread.sleep(3000);
		System.out.println(Thread.currentThread().getName() + ":"  + "火鍋食材準備好了");
		String shicai = "火鍋食材";

		// 開水已經稍好,我們取得燒好的開水
		String boilWater = futureTask.get();

		System.out.println(Thread.currentThread().getName() + ":"  + boilWater + "和" + shicai + "已經準備好,我們可以開始打火鍋啦");
	}
}

執行結果如下截圖,符合我們的預期:

從以上代碼中可以看到,我們使用Future主要有以下步驟:

  1. 新建一個Callable匿名函數實現類對象,我們的業務邏輯在Callablecall方法中實現,其中Callable的泛型是返回結果類型;
  2. 然後把Callable匿名函數對象作為FutureTask的構造參數傳入,構建一個futureTask對象;
  3. 然後再把futureTask對象作為Thread構造參數傳入並開啟這個線程執行去執行業務邏輯;
  4. 最後我們調用futureTask對象的get方法得到業務邏輯執行結果。

可以看到跟Future使用有關的JDK類主要有FutureTaskCallable兩個,下面主要對FutureTask進行源碼分析。

擴展: 還有一種使用Future的方式是將Callable實現類提交給線程池執行的方式,這裏不再介紹,自行百度即可。

3 FutureTask類結構分析

我們先來看下FutureTask的類結構:

可以看到FutureTask實現了RunnableFuture接口,而RunnableFuture接口又繼承了FutureRunnable接口。因為FutureTask間接實現了Runnable接口,因此可以作為任務被線程Thread執行;此外,最重要的一點就是FutureTask還間接實現了Future接口,因此還可以獲得任務執行的結果。下面我們就來簡單看看這幾個接口的相關api

// Runnable.java

@FunctionalInterface
public interface Runnable {
    // 執行線程任務
    public abstract void run();
}

Runnable沒啥好說的,相信大家都已經很熟悉了。

// Future.java

public interface Future<V> {
    /**
     * 嘗試取消線程任務的執行,分為以下幾種情況:
     * 1)如果線程任務已經完成或已經被取消或其他原因不能被取消,此時會失敗並返回false;
     * 2)如果任務還未開始執行,此時執行cancel方法,那麼任務將被取消執行,此時返回true;TODO 此時對應任務狀態state的哪種狀態???不懂!!
     * 3)如果任務已經開始執行,那麼mayInterruptIfRunning這個參數將決定是否取消任務的執行。
     *    這裏值得注意的是,cancel(true)實質並不能真正取消線程任務的執行,而是發出一個線程
     *    中斷的信號,一般需要結合Thread.currentThread().isInterrupted()來使用。
     */
    boolean cancel(boolean mayInterruptIfRunning);
    /**
     * 判斷任務是否被取消,在執行任務完成前被取消,此時會返回true
     */
    boolean isCancelled();
    /**
     * 這個方法不管任務正常停止,異常還是任務被取消,總是返回true。
     */
    boolean isDone();
    /**
     * 獲取任務執行結果,注意是阻塞等待獲取任務執行結果。
     */
    V get() throws InterruptedException, ExecutionException;
    /**
     * 獲取任務執行結果,注意是阻塞等待獲取任務執行結果。
     * 只不過在規定的時間內未獲取到結果,此時會拋出超時異常
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Future接口象徵著異步執行任務的結果即執行一個耗時任務完全可以另起一個線程執行,然後此時我們可以去做其他事情,做完其他事情我們再調用Future.get()方法獲取結果即可,此時若異步任務還沒結束,此時會一直阻塞等待,直到異步任務執行完獲取到結果。

// RunnableFuture.java

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

RunnableFutureFutureRunnable接口的組合,即這個接口表示又可以被線程異步執行,因為實現了Runnable接口,又可以獲得線程異步任務的執行結果,因為實現了Future接口。因此解決了Runnable異步任務沒有返回結果的缺陷。

接下來我們來看下FutureTaskFutureTask實現了RunnableFuture接口,因此是FutureRunnable接口的具體實現類,是一個可被取消的異步線程任務,提供了Future的基本實現,即異步任務執行后我們能夠獲取到異步任務的執行結果,是我們接下來分析的重中之重。FutureTask可以包裝一個CallableRunnable對象,此外,FutureTask除了可以被線程執行外,還可以被提交給線程池執行。

我們先看下FutureTask類的api,其中重點方法已經紅框框出。

上圖中FutureTaskrun方法是被線程異步執行的方法,get方法即是取得異步任務執行結果的方法,還有cancel方法是取消任務執行的方法。接下來我們主要對這三個方法進行重點分析。

思考

  1. FutureTask覆寫的run方法的返回類型依然是void,表示沒有返回值,那麼FutureTaskget方法又是如何獲得返回值的呢?
  2. FutureTaskcancel方法能真正取消線程異步任務的執行么?什麼情況下能取消?

因為FutureTask異步任務執行結果還跟Callable接口有關,因此我們再來看下Callable接口:

// Callable.java

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     */
    V call() throws Exception;
}

我們都知道,Callable<V>接口和Runnable接口都可以被提交給線程池執行,唯一不同的就是Callable<V>接口是有返回結果的,其中的泛型V就是返回結果,而Runnable接口是沒有返回結果的。

思考: 一般情況下,Runnable接口實現類才能被提交給線程池執行,為何Callable接口實現類也可以被提交給線程池執行?想想線程池的submit方法內部有對Callable做適配么?

4 FutureTask源碼分析

4.1 FutureTask成員變量

我們首先來看下FutureTask的成員變量有哪些,理解這些成員變量對後面的源碼分析非常重要。

// FutureTask.java

/** 封裝的Callable對象,其call方法用來執行異步任務 */
private Callable<V> callable;
/** 在FutureTask裏面定義一個成員變量outcome,用來裝異步任務的執行結果 */
private Object outcome; // non-volatile, protected by state reads/writes
/** 用來執行callable任務的線程 */
private volatile Thread runner;
/** 線程等待節點,reiber stack的一種實現 */
private volatile WaitNode waiters;
/** 任務執行狀態 */
private volatile int state;

// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
// 對應成員變量state的偏移地址
private static final long stateOffset;
// 對應成員變量runner的偏移地址
private static final long runnerOffset;
// 對應成員變量waiters的偏移地址
private static final long waitersOffset;

這裏我們要重點關注下FutureTaskCallable成員變量,因為FutureTask的異步任務最終是委託給Callable去實現的。

思考

  1. FutureTask的成員變量runner,waitersstate都被volatile修飾,我們可以思考下為什麼這三個成員變量需要被volatile修飾,而其他成員變量又不用呢?volatile關鍵字的作用又是什麼呢?
  2. 既然已經定義了成員變量runner,waitersstate了,此時又定義了stateOffset,runnerOffsetwaitersOffset變量分別對應runner,waitersstate的偏移地址,為何要多此一舉呢?

我們再來看看stateOffset,runnerOffsetwaitersOffset變量這三個變量的初始化過程:

// FutureTask.java

static {
    try {
        UNSAFE = sun.misc.Unsafe.getUnsafe();
        Class<?> k = FutureTask.class;
        stateOffset = UNSAFE.objectFieldOffset
            (k.getDeclaredField("state"));
        runnerOffset = UNSAFE.objectFieldOffset
            (k.getDeclaredField("runner"));
        waitersOffset = UNSAFE.objectFieldOffset
            (k.getDeclaredField("waiters"));
    } catch (Exception e) {
        throw new Error(e);
    }
    }

4.2 FutureTask的狀態變化

前面講了FutureTask的成員變量,有一個表示狀態的成員變量state我們要重點關注下,state變量表示任務執行的狀態。

// FutureTask.java

/** 任務執行狀態 */
private volatile int state;
/** 任務新建狀態 */
private static final int NEW          = 0;
/** 任務正在完成狀態,是一個瞬間過渡狀態 */
private static final int COMPLETING   = 1;
/** 任務正常結束狀態 */
private static final int NORMAL       = 2;
/** 任務執行異常狀態 */
private static final int EXCEPTIONAL  = 3;
/** 任務被取消狀態,對應cancel(false) */
private static final int CANCELLED    = 4;
/** 任務中斷狀態,是一個瞬間過渡狀態 */
private static final int INTERRUPTING = 5;
/** 任務被中斷狀態,對應cancel(true) */
private static final int INTERRUPTED  = 6;

可以看到任務狀態變量state有以上7種狀態,0-6分別對應着每一種狀態。任務狀態一開始是NEW,然後由FutureTask的三個方法set,setExceptioncancel來設置狀態的變化,其中狀態變化有以下四種情況:

  1. NEW -> COMPLETING -> NORMAL:這個狀態變化表示異步任務的正常結束,其中COMPLETING是一個瞬間臨時的過渡狀態,由set方法設置狀態的變化;
  2. NEW -> COMPLETING -> EXCEPTIONAL:這個狀態變化表示異步任務執行過程中拋出異常,由setException方法設置狀態的變化;
  3. NEW -> CANCELLED:這個狀態變化表示被取消,即調用了cancel(false),由cancel方法來設置狀態變化;
  4. NEW -> INTERRUPTING -> INTERRUPTED:這個狀態變化表示被中斷,即調用了cancel(true),由cancel方法來設置狀態變化。

4.3 FutureTask構造函數

FutureTask有兩個構造函數,我們分別來看看:

// FutureTask.java

// 第一個構造函數
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

可以看到,這個構造函數在我們前面舉的“打火鍋”的例子代碼中有用到,就是Callable成員變量賦值,在異步執行任務時再調用Callable.call方法執行異步任務邏輯。此外,此時給任務狀態state賦值為NEW,表示任務新建狀態。

我們再來看下FutureTask的另外一個構造函數:

// FutureTask.java

// 另一個構造函數
public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}

這個構造函數在執行Executors.callable(runnable, result)時是通過適配器RunnableAdapter來將Runnable對象runnable轉換成Callable對象,然後再分別給callablestate變量賦值。

注意,這裏我們需要記住的是FutureTask新建時,此時的任務狀態stateNEW就好了。

4.4 FutureTask.run方法,用來執行異步任務

前面我們有講到FutureTask間接實現了Runnable接口,覆寫了Runnable接口的run方法,因此該覆寫的run方法是提交給線程來執行的,同時,該run方法正是執行異步任務邏輯的方法,那麼,執行完run方法又是如何保存異步任務執行的結果的呢?

我們現在着重來分析下run方法:

// FutureTask.java

public void run() {
    // 【1】,為了防止多線程併發執行異步任務,這裏需要判斷線程滿不滿足執行異步任務的條件,有以下三種情況:
    // 1)若任務狀態state為NEW且runner為null,說明還未有線程執行過異步任務,此時滿足執行異步任務的條件,
    // 此時同時調用CAS方法為成員變量runner設置當前線程的值;
    // 2)若任務狀態state為NEW且runner不為null,任務狀態雖為NEW但runner不為null,說明有線程正在執行異步任務,
    // 此時不滿足執行異步任務的條件,直接返回;
    // 1)若任務狀態state不為NEW,此時不管runner是否為null,說明已經有線程執行過異步任務,此時沒必要再重新
    // 執行一次異步任務,此時不滿足執行異步任務的條件;
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))
        return;
    try {
        // 拿到之前構造函數傳進來的callable實現類對象,其call方法封裝了異步任務執行的邏輯
        Callable<V> c = callable;
        // 若任務還是新建狀態的話,那麼就調用異步任務
        if (c != null && state == NEW) {
            // 異步任務執行結果
            V result;
            // 異步任務執行成功還是始遍標誌
            boolean ran;
            try {
                // 【2】,執行異步任務邏輯,並把執行結果賦值給result
                result = c.call();
                // 若異步任務執行過程中沒有拋出異常,說明異步任務執行成功,此時設置ran標誌為true
                ran = true;
            } catch (Throwable ex) {
                result = null;
                // 異步任務執行過程拋出異常,此時設置ran標誌為false
                ran = false;
                // 【3】設置異常,裏面也設置state狀態的變化
                setException(ex);
            }
            // 【3】若異步任務執行成功,此時設置異步任務執行結果,同時也設置狀態的變化
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        // 異步任務正在執行過程中,runner一直是非空的,防止併發調用run方法,前面有調用cas方法做判斷的
        // 在異步任務執行完后,不管是正常結束還是異常結束,此時設置runner為null
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        // 線程執行異步任務后的任務狀態
        int s = state;
        // 【4】如果執行了cancel(true)方法,此時滿足條件,
        // 此時調用handlePossibleCancellationInterrupt方法處理中斷
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

可以看到執行異步任務的run方法主要分為以下四步來執行:

  1. 判斷線程是否滿足執行異步任務的條件:為了防止多線程併發執行異步任務,這裏需要判斷線程滿不滿足執行異步任務的條件;
  2. 若滿足條件,執行異步任務:因為異步任務邏輯封裝在Callable.call方法中,此時直接調用Callable.call方法執行異步任務,然後返回執行結果;
  3. 根據異步任務的執行情況做不同的處理:1) 若異步任務執行正常結束,此時調用set(result);來設置任務執行結果;2)若異步任務執行拋出異常,此時調用setException(ex);來設置異常,詳細分析請見4.4.1小節
  4. 異步任務執行完后的善後處理工作:不管異步任務執行成功還是失敗,若其他線程有調用FutureTask.cancel(true),此時需要調用handlePossibleCancellationInterrupt方法處理中斷,詳細分析請見4.4.2小節

這裏值得注意的是判斷線程滿不滿足執行異步任務條件時,runner是否為null是調用UNSAFECAS方法compareAndSwapObject來判斷和設置的,同時compareAndSwapObject是通過成員變量runner的偏移地址runnerOffset來給runner賦值的,此外,成員變量runner被修飾為volatile是在多線程的情況下, 一個線程的volatile修飾變量的設值能夠立即刷進主存,因此值便可被其他線程可見。

4.4.1 FutureTask的set和setException方法

下面我們來看下當異步任務執行正常結束時,此時會調用set(result);方法:

// FutureTask.java

protected void set(V v) {
    // 【1】調用UNSAFE的CAS方法判斷任務當前狀態是否為NEW,若為NEW,則設置任務狀態為COMPLETING
    // 【思考】此時任務不能被多線程併發執行,什麼情況下會導致任務狀態不為NEW?
    // 答案是只有在調用了cancel方法的時候,此時任務狀態不為NEW,此時什麼都不需要做,
    // 因此需要調用CAS方法來做判斷任務狀態是否為NEW
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        // 【2】將任務執行結果賦值給成員變量outcome
        outcome = v;
        // 【3】將任務狀態設置為NORMAL,表示任務正常結束
        UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
        // 【4】調用任務執行完成方法,此時會喚醒阻塞的線程,調用done()方法和清空等待線程鏈表等
        finishCompletion();
    }
}

可以看到當異步任務正常執行結束后,且異步任務沒有被cancel的情況下,此時會做以下事情:將任務執行結果保存到FutureTask的成員變量outcome中的,賦值結束後會調用finishCompletion方法來喚醒阻塞的線程(哪裡來的阻塞線程?後面會分析),值得注意的是這裏對應的任務狀態變化是NEW -> COMPLETING -> NORMAL

我們繼續來看下當異步任務執行過程中拋出異常,此時會調用setException(ex);方法。

// FutureTask.java

protected void setException(Throwable t) {
    // 【1】調用UNSAFE的CAS方法判斷任務當前狀態是否為NEW,若為NEW,則設置任務狀態為COMPLETING
    // 【思考】此時任務不能被多線程併發執行,什麼情況下會導致任務狀態不為NEW?
    // 答案是只有在調用了cancel方法的時候,此時任務狀態不為NEW,此時什麼都不需要做,
    // 因此需要調用CAS方法來做判斷任務狀態是否為NEW
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        // 【2】將異常賦值給成員變量outcome
        outcome = t;
        // 【3】將任務狀態設置為EXCEPTIONAL
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
        // 【4】調用任務執行完成方法,此時會喚醒阻塞的線程,調用done()方法和清空等待線程鏈表等
        finishCompletion();
    }
}

可以看到setException(Throwable t)的代碼邏輯跟前面的set(V v)幾乎一樣,不同的是任務執行過程中拋出異常,此時是將異常保存到FutureTask的成員變量outcome中,還有,值得注意的是這裏對應的任務狀態變化是NEW -> COMPLETING -> EXCEPTIONAL

因為異步任務不管正常還是異常結束,此時都會調用FutureTaskfinishCompletion方法來喚醒喚醒阻塞的線程,這裏阻塞的線程是指我們調用Future.get方法時若異步任務還未執行完,此時該線程會阻塞。

// FutureTask.java

private void finishCompletion() {
    // assert state > COMPLETING;
    // 取出等待線程鏈表頭節點,判斷頭節點是否為null
    // 1)若線程鏈表頭節點不為空,此時以“後進先出”的順序(棧)移除等待的線程WaitNode節點
    // 2)若線程鏈表頭節點為空,說明還沒有線程調用Future.get()方法來獲取任務執行結果,固然不用移除
    for (WaitNode q; (q = waiters) != null;) {
        // 調用UNSAFE的CAS方法將成員變量waiters設置為空
        if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
            for (;;) {
                // 取出WaitNode節點的線程
                Thread t = q.thread;
                // 若取出的線程不為null,則將該WaitNode節點線程置空,且喚醒正在阻塞的該線程
                if (t != null) {
                    q.thread = null;
                    //【重要】喚醒正在阻塞的該線程
                    LockSupport.unpark(t);
                }
                // 繼續取得下一個WaitNode線程節點
                WaitNode next = q.next;
                // 若沒有下一個WaitNode線程節點,說明已經將所有等待的線程喚醒,此時跳出for循環
                if (next == null)
                    break;
                // 將已經移除的線程WaitNode節點的next指針置空,此時好被垃圾回收
                q.next = null; // unlink to help gc
                // 再把下一個WaitNode線程節點置為當前線程WaitNode頭節點
                q = next;
            }
            break;
        }
    }
    // 不管任務正常執行還是拋出異常,都會調用done方法
    done();
    // 因為異步任務已經執行完且結果已經保存到outcome中,因此此時可以將callable對象置空了
    callable = null;        // to reduce footprint
}

finishCompletion方法的作用就是不管異步任務正常還是異常結束,此時都要喚醒且移除線程等待鏈表的等待線程節點,這個鏈表實現的是一個是Treiber stack,因此喚醒(移除)的順序是”後進先出”即後面先來的線程先被先喚醒(移除),關於這個線程等待鏈表是如何成鏈的,後面再繼續分析。

4.4.2 FutureTask的handlePossibleCancellationInterrupt方法

4.4小節分析的run方法里的最後有一個finally塊,此時若任務狀態state >= INTERRUPTING,此時說明有其他線程執行了cancel(true)方法,此時需要讓出CPU執行的時間片段給其他線程執行,我們來看下具體的源碼:

// FutureTask.java

private void handlePossibleCancellationInterrupt(int s) {
    // It is possible for our interrupter to stall before getting a
    // chance to interrupt us.  Let's spin-wait patiently.
    // 當任務狀態是INTERRUPTING時,此時讓出CPU執行的機會,讓其他線程執行
    if (s == INTERRUPTING)
        while (state == INTERRUPTING)
            Thread.yield(); // wait out pending interrupt

    // assert state == INTERRUPTED;

    // We want to clear any interrupt we may have received from
    // cancel(true).  However, it is permissible to use interrupts
    // as an independent mechanism for a task to communicate with
    // its caller, and there is no way to clear only the
    // cancellation interrupt.
    //
    // Thread.interrupted();
}

思考: 為啥任務狀態是INTERRUPTING時,此時就要讓出CPU執行的時間片段呢?還有為什麼要在義務任務執行后才調用handlePossibleCancellationInterrupt方法呢?

4.5 FutureTask.get方法,獲取任務執行結果

前面我們起一個線程在其`run`方法中執行異步任務后,此時我們可以調用`FutureTask.get`方法來獲取異步任務執行的結果。

// FutureTask.java

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    // 【1】若任務狀態<=COMPLETING,說明任務正在執行過程中,此時可能正常結束,也可能遇到異常
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    // 【2】最後根據任務狀態來返回任務執行結果,此時有三種情況:1)任務正常執行;2)任務執行異常;3)任務被取消
    return report(s);
}

可以看到,如果任務狀態state<=COMPLETING,說明異步任務正在執行過程中,此時會調用awaitDone方法阻塞等待;當任務執行完后,此時再調用report方法來報告任務結果,此時有三種情況:1)任務正常執行;2)任務執行異常;3)任務被取消。

4.5.1 FutureTask.awaitDone方法

FutureTask.awaitDone方法會阻塞獲取異步任務執行結果的當前線程,直到異步任務執行完成。

// FutureTask.java

private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    // 計算超時結束時間
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    // 線程鏈表頭節點
    WaitNode q = null;
    // 是否入隊
    boolean queued = false;
    // 死循環
    for (;;) {
        // 如果當前獲取任務執行結果的線程被中斷,此時移除該線程WaitNode鏈表節點,並拋出InterruptedException
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        // 【5】如果任務狀態>COMPLETING,此時返回任務執行結果,其中此時任務可能正常結束(NORMAL),可能拋出異常(EXCEPTIONAL)
        // 或任務被取消(CANCELLED,INTERRUPTING或INTERRUPTED狀態的一種)
        if (s > COMPLETING) {
            // 【問】此時將當前WaitNode節點的線程置空,其中在任務結束時也會調用finishCompletion將WaitNode節點的thread置空,
            // 這裏為什麼又要再調用一次q.thread = null;呢?
            // 【答】因為若很多線程來獲取任務執行結果,在任務執行完的那一刻,此時獲取任務的線程要麼已經在線程等待鏈表中,要麼
            // 此時還是一個孤立的WaitNode節點。在線程等待鏈表中的的所有WaitNode節點將由finishCompletion來移除(同時喚醒)所有
            // 等待的WaitNode節點,以便垃圾回收;而孤立的線程WaitNode節點此時還未阻塞,因此不需要被喚醒,此時只要把其屬性置為
            // null,然後其有沒有被誰引用,因此可以被GC。
            if (q != null)
                q.thread = null;
            // 【重要】返回任務執行結果
            return s;
        }
        // 【4】若任務狀態為COMPLETING,此時說明任務正在執行過程中,此時獲取任務結果的線程需讓出CPU執行時間片段
        else if (s == COMPLETING) // cannot time out yet
            Thread.yield();
        // 【1】若當前線程還沒有進入線程等待鏈表的WaitNode節點,此時新建一個WaitNode節點,並把當前線程賦值給WaitNode節點的thread屬性
        else if (q == null)
            q = new WaitNode();
        // 【2】若當前線程等待節點還未入線程等待隊列,此時加入到該線程等待隊列的頭部
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        // 若有超時設置,那麼處理超時獲取任務結果的邏輯
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            LockSupport.parkNanos(this, nanos);
        }
        // 【3】若沒有超時設置,此時直接阻塞當前線程
        else
            LockSupport.park(this);
    }
}

FutureTask.awaitDone方法主要做的事情總結如下:

  1. 首先awaitDone方法裏面是一個死循環;
  2. 若獲取結果的當前線程被其他線程中斷,此時移除該線程WaitNode鏈表節點,並拋出InterruptedException;
  3. 如果任務狀態state>COMPLETING,此時返回任務執行結果;
  4. 若任務狀態為COMPLETING,此時獲取任務結果的線程需讓出CPU執行時間片段;
  5. q == null,說明當前線程還未設置到WaitNode節點,此時新建WaitNode節點並設置其thread屬性為當前線程;
  6. queued==false,說明當前線程WaitNode節點還未加入線程等待鏈表,此時加入該鏈表的頭部;
  7. timed設置為true時,此時該方法具有超時功能,關於超時的邏輯這裏不詳細分析;
  8. 當前面6個條件都不滿足時,此時阻塞當前線程。

我們分析到這裏,可以直到執行異步任務只能有一個線程來執行,而獲取異步任務結果可以多線程來獲取,當異步任務還未執行完時,此時獲取異步任務結果的線程會加入線程等待鏈表中,然後調用調用LockSupport.park(this);方法阻塞當前線程。直到異步任務執行完成,此時會調用finishCompletion方法來喚醒並移除線程等待鏈表的每個WaitNode節點,這裏這裏喚醒(移除)WaitNode節點的線程是從鏈表頭部開始的,前面我們也已經分析過。

還有一個特別需要注意的就是awaitDone方法裏面是一個死循環,當一個獲取異步任務的線程進來后可能會多次進入多個條件分支執行不同的業務邏輯,也可能只進入一個條件分支。下面分別舉兩種可能的情況進行說明:

情況1
當獲取異步任務結果的線程進來時,此時異步任務還未執行完即state=NEW且沒有超時設置時:

  1. 第一次循環:此時q = null,此時進入上面代碼標號【1】的判斷分支,即為當前線程新建一個WaitNode節點;
  2. 第二次循環:此時queued = false,此時進入上面代碼標號【2】的判斷分支,即將之前新建的WaitNode節點加入線程等待鏈表中;
  3. 第三次循環:此時進入上面代碼標號【3】的判斷分支,即阻塞當前線程;
  4. 第四次循環:加入此時異步任務已經執行完,此時進入上面代碼標號【5】的判斷分支,即返回異步任務執行結果。

情況2
當獲取異步任務結果的線程進來時,此時異步任務已經執行完即state>COMPLETING且沒有超時設置時,此時直接進入上面代碼標號【5】的判斷分支,即直接返回異步任務執行結果即可,也不用加入線程等待鏈表了。

4.5.2 FutureTask.report方法

get方法中,當異步任務執行結束后即不管異步任務正常還是異常結束,亦或是被cancel,此時獲取異步任務結果的線程都會被喚醒,因此會繼續執行FutureTask.report方法報告異步任務的執行情況,此時可能會返回結果,也可能會拋出異常。

// FutureTask.java

private V report(int s) throws ExecutionException {
    // 將異步任務執行結果賦值給x,此時FutureTask的成員變量outcome要麼保存着
    // 異步任務正常執行的結果,要麼保存着異步任務執行過程中拋出的異常
    Object x = outcome;
    // 【1】若異步任務正常執行結束,此時返回異步任務執行結果即可
    if (s == NORMAL)
        return (V)x;
    // 【2】若異步任務執行過程中,其他線程執行過cancel方法,此時拋出CancellationException異常
    if (s >= CANCELLED)
        throw new CancellationException();
    // 【3】若異步任務執行過程中,拋出異常,此時將該異常轉換成ExecutionException后,重新拋出。
    throw new ExecutionException((Throwable)x);
}

4.6 FutureTask.cancel方法,取消執行任務

我們最後再來看下FutureTask.cancel方法,我們一看到FutureTask.cancel方法,肯定一開始就天真的認為這是一個可以取消異步任務執行的方法,如果我們這樣認為的話,只能說我們猜對了一半。

// FutureTask.java

public boolean cancel(boolean mayInterruptIfRunning) {
    // 【1】判斷當前任務狀態,若state == NEW時根據mayInterruptIfRunning參數值給當前任務狀態賦值為INTERRUPTING或CANCELLED
    // a)當任務狀態不為NEW時,說明異步任務已經完成,或拋出異常,或已經被取消,此時直接返回false。
    // TODO 【問題】此時若state = COMPLETING呢?此時為何也直接返回false,而不能發出中斷異步任務線程的中斷信號呢??
    // TODO 僅僅因為COMPLETING是一個瞬時態嗎???
    // b)當前僅當任務狀態為NEW時,此時若mayInterruptIfRunning為true,此時任務狀態賦值為INTERRUPTING;否則賦值為CANCELLED。
    if (!(state == NEW &&
          UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
              mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
        return false;
    try {    // in case call to interrupt throws exception
        // 【2】如果mayInterruptIfRunning為true,此時中斷執行異步任務的線程runner(還記得執行異步任務時就把執行異步任務的線程就賦值給了runner成員變量嗎)
        if (mayInterruptIfRunning) {
            try {
                Thread t = runner;
                if (t != null)
                    // 中斷執行異步任務的線程runner
                    t.interrupt();
            } finally { // final state
                // 最後任務狀態賦值為INTERRUPTED
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
            }
        }
    // 【3】不管mayInterruptIfRunning為true還是false,此時都要調用finishCompletion方法喚醒阻塞的獲取異步任務結果的線程並移除線程等待鏈表節點
    } finally {
        finishCompletion();
    }
    // 返回true
    return true;
}

以上代碼中,當異步任務狀態state != NEW時,說明異步任務已經正常執行完或已經異常結束亦或已經被cancel,此時直接返回false;當異步任務狀態state = NEW時,此時又根據mayInterruptIfRunning參數是否為true分為以下兩種情況:

  1. mayInterruptIfRunning = false時,此時任務狀態state直接被賦值為CANCELLED,此時不會對執行異步任務的線程發出中斷信號,值得注意的是這裏對應的任務狀態變化是NEW -> CANCELLED
  2. mayInterruptIfRunning = true時,此時會對執行異步任務的線程發出中斷信號,值得注意的是這裏對應的任務狀態變化是NEW -> INTERRUPTING -> INTERRUPTED

最後不管mayInterruptIfRunningtrue還是false,此時都要調用finishCompletion方法喚醒阻塞的獲取異步任務結果的線程並移除線程等待鏈表節點。

FutureTask.cancel源碼中我們可以得出答案,該方法並不能真正中斷正在執行異步任務的線程,只能對執行異步任務的線程發出中斷信號。如果執行異步任務的線程處於sleepwaitjoin的狀態中,此時會拋出InterruptedException異常,該線程可以被中斷;此外,如果異步任務需要在while循環執行的話,此時可以結合以下代碼來結束異步任務線程,即執行異步任務的線程被中斷時,此時Thread.currentThread().isInterrupted()返回true,不滿足while循環條件因此退出循環,結束異步任務執行線程,如下代碼:

public Integer call() throws Exception {
    while (!Thread.currentThread().isInterrupted()) {
        // 業務邏輯代碼
        System.out.println("running...");

    }
    return 666;
}

注意:調用了FutureTask.cancel方法,只要返回結果是true,假如異步任務線程雖然不能被中斷,即使異步任務線程正常執行完畢,返回了執行結果,此時調用FutureTask.get方法也不能夠獲取異步任務執行結果,此時會拋出CancellationException異常。請問知道這是為什麼嗎?

因為調用了FutureTask.cancel方法,只要返回結果是true,此時的任務狀態為CANCELLEDINTERRUPTED,同時必然會執行finishCompletion方法,而finishCompletion方法會喚醒獲取異步任務結果的線程等待列表的線程,而獲取異步任務結果的線程喚醒后發現狀態s >= CANCELLED,此時就會拋出CancellationException異常了。

5 總結

好了,本篇文章對FutureTask的源碼分析就到此結束了,下面我們再總結下FutureTask的實現邏輯:

  1. 我們實現Callable接口,在覆寫的call方法中定義需要執行的業務邏輯;
  2. 然後把我們實現的Callable接口實現對象傳給FutureTask,然後FutureTask作為異步任務提交給線程執行;
  3. 最重要的是FutureTask內部維護了一個狀態state,任何操作(異步任務正常結束與否還是被取消)都是圍繞着這個狀態進行,並隨時更新state任務的狀態;
  4. 只能有一個線程執行異步任務,當異步任務執行結束后,此時可能正常結束,異常結束或被取消。
  5. 可以多個線程併發獲取異步任務執行結果,當異步任務還未執行完,此時獲取異步任務的線程將加入線程等待列表進行等待;
  6. 當異步任務線程執行結束后,此時會喚醒獲取異步任務執行結果的線程,注意喚醒順序是”後進先出”即後面加入的阻塞線程先被喚醒。
  7. 當我們調用FutureTask.cancel方法時並不能真正停止執行異步任務的線程,只是發出中斷線程的信號。但是只要cancel方法返回true,此時即使異步任務能正常執行完,此時我們調用get方法獲取結果時依然會拋出CancellationException異常。

擴展: 前面我們提到了FutureTaskrunner,waitersstate都是用volatile關鍵字修飾,說明這三個變量都是多線程共享的對象(成員變量),會被多線程操作,此時用volatile關鍵字修飾是為了一個線程操作volatile屬性變量值后,能夠及時對其他線程可見。此時多線程操作成員變量僅僅用了volatile關鍵字仍然會有線程安全問題的,而此時Doug Lea老爺子沒有引入任何線程鎖,而是採用了UnsafeCAS方法來代替鎖操作,確保線程安全性。

6 分析FutureTask源碼,我們能學到什麼?

我們分析源碼的目的是什麼?除了弄懂FutureTask的內部實現原理外,我們還要借鑒大佬寫寫框架源碼的各種技巧,只有這樣,我們才能成長。

分析了FutureTask源碼,我們可以從中學到:

  1. 利用LockSupport來實現線程的阻塞\喚醒機制;
  2. 利用volatileUNSAFECAS方法來實現線程共享變量的無鎖化操作;
  3. 若要編寫超時異常的邏輯可以參考FutureTaskget(long timeout, TimeUnit unit)的實現邏輯;
  4. 多線程獲取某一成員變量結果時若需要等待時的線程等待鏈表的邏輯實現;
  5. 某一異步任務在某一時刻只能由單一線程執行的邏輯實現;
  6. FutureTask中的任務狀態satate的變化處理的邏輯實現。

以上列舉的幾點都是我們可以學習參考的地方。

若您覺得不錯,請無情的轉發和點贊吧!

【源碼筆記】Github地址:

https://github.com/yuanmabiji/Java-SourceCode-Blogs

公眾號【源碼筆記】,專註於Java後端系列框架的源碼分析。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家公司費用,距離,噸數怎麼算?達人教你簡易估價知識!

※教你寫出一流的銷售文案?

※超省錢租車方案

Java 數組最佳指南,快收藏讓它吃灰

兩年前,我甚至寫過一篇文章,吐槽數組在 Java 中挺雞肋的,因為有 List 誰用數組啊,現在想想那時候的自己好幼稚,好可笑。因為我只看到了表面現象,實際上呢,List 的內部仍然是通過數組實現的,比如說 ArrayList,在它的源碼里可以看到下面這些內容:

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 */

transient Object[] elementData; // non-private to simplify nested class access

/**
 * The size of the ArrayList (the number of elements it contains).
 *
 * @serial
 */

private int size;

數組在 Java 中,必須算是核心,神一般的存在。

01、什麼是數組

按照 Javadoc 給出的解釋,數組是一個對象,它包含了一組固定數量的元素,並且這些元素的類型是相同的。數組會按照索引的方式將元素放在指定的位置上,意味着我們可以通過索引來訪問到這些元素。在 Java 中,索引是從 0 開始的。

我們可以將數組理解為一個個整齊排列的單元格,每個單元格裏面存放着一個元素。

數組元素的類型可以是基本數據類型(比如說 int、double),也可以是引用數據類型(比如說 String),包括自定義類型的對象。

了解了數組的定義后,讓我們來深入地研究一下數組的用法。

在 Java 中,數組的聲明方式有兩種。

先來看第一種:

int[] anArray;

再來看第二種:

int anOtherArray[];

不同之處就在於中括號的位置,是緊跟類型,還是放在變量名的後面。前者比後者的使用頻率更高一些。

接下來就該看看怎麼初始化數組了,同樣有多種方式可以初始化數組,比如說最常見的是:

int[] anArray = new int[10];

使用了 new 關鍵字,對吧?這就意味着數組的確是一個對象。然後,在方括號中指定了數組的長度,這是必須的。

這時候,數組中的每個元素都會被初始化為默認值,int 類型的就為 0,Object 類型的就為 null。

另外,還可以使用大括號的方式,直接初始化數組中的元素:

int anOtherArray[] = new int[] {12345};

這時候,數組的元素分別是 1、2、3、4、5,索引依次是 0、1、2、3、4。

02、訪問數組

前面提到過,可以通過索引來訪問數組的元素,就像下面這樣:

anArray[0] = 10;
System.out.println(anArray[0]);

通過數組的變量名,加上中括號,加上元素的索引,就可以訪問到數組,通過“=”操作符進行賦值。

如果索引的值超出了數組的界限,就會拋出 ArrayIndexOutOfBoundException,關於這方面的知識,我之前特意寫過一篇文章,如果你感興趣的話,可以跳轉過去看看。

為什麼會發生ArrayIndexOutOfBoundsException

我覺得原因挺有意思的。

既然數組的索引是從 0 開始,那就是到數組的 length - 1 結束,不要使用超出這個範圍內的索引訪問數組,就不會拋出數組越界的異常了。

03、遍曆數組

當數組的元素非常多的時候,逐個訪問數組就太辛苦了,所以需要通過遍歷的方式。

第一種,使用 for 循環:

int anOtherArray[] = new int[] {12345};
for (int i = 0; i < anOtherArray.length; i++) {
    System.out.println(anOtherArray[i]);
}

通過 length 屬性獲取到數組的長度,然後索引從 0 開始遍歷,就得到了數組的所有元素。

第二種,使用 for-each 循環:

for (int element : anOtherArray) {
    System.out.println(element);
}

如果不需要關心索引的話(意味着不需要修改數組的某個元素),使用 for-each 遍歷更簡潔一些。當然,也可以使用 while 和 do-while 循環。

04、可變參數

可變參數用於將任意數量的參數傳遞給方法:

void varargsMethod(String... varargs) {}

varargsMethod() 方法可以傳遞任意數量的字符串參數,可以是 0 個或者 N 個,本質上,可變參數就是通過數組實現的,為了證明這一點,我們可以通過 jad 反編譯一下字節碼:

public class VarargsDemo
{

    public VarargsDemo()
    
{
    }

    transient void varargsMethod(String as[])
    
{
    }
}

所以我們其實可以直接將數組作為參數傳遞給可變參數的方法:

VarargsDemo demo = new VarargsDemo();
String[] anArray = new String[] {"沉默王二""一枚有趣的程序員"};
demo.varargsMethod(anArray);

也可以直接傳遞多個字符串,通過逗號隔開的方式:

demo.varargsMethod("沉默王二""一枚有趣的程序員");

05、把數組轉成 List

List 封裝了很多常用的方法,方便我們對集合進行一些操作,而如果直接操作數組的話,多有不便,因此有時候我們需要把數組轉成 List。

最原始的方式,就是通過遍曆數組的方式,一個個將數組添加到 List 中。

int[] anArray = new int[] {12345};

List<Integer> aList = new ArrayList<>();
for (int element : anArray) {
    aList.add(element);
}

更優雅的方式是通過 Arrays 類的 asList() 方法:

List<Integer> aList = Arrays.asList(anArray);

但需要注意的是,該方法返回的 ArrayList 並不是 java.util.ArrayList,它其實是 Arrays 類的一個內部類:

private static class ArrayList<Eextends AbstractList<E>
        implements RandomAccessjava.io.Serializable
{}

如果需要添加元素或者刪除元素的話,最好把它轉成 java.util.ArrayList

new ArrayList<>(Arrays.asList(anArray));

06、把數組轉成 Stream

Java 8 新增了 Stream 流的概念,這就意味着我們也可以將數組轉成 Stream 進行操作,而不是 List。

String[] anArray = new String[] {"沉默王二""一枚有趣的程序員""好好珍重他"};
Stream<String> aStream = Arrays.stream(anArray);

也可以直接對數組的元素進行剪輯,通過指定索引的方式:

Stream<String> anotherStream = Arrays.stream(anArray, 13);

結果包含”一枚有趣的程序員”和”好好珍重他”,1 這個索引位置包括,3 這個索引位置不包括。

07、數組排序

Arrays 類提供了一個 sort() 方法,可以對數組進行排序。

  • 基本數據類型按照升序排列
  • 實現了 Comparable 接口的對象按照 compareTo() 的排序

來看第一個例子:

int[] anArray = new int[] {52148};
Arrays.sort(anArray);

排序后的結果如下所示:

[12458]

來看第二個例子:

String[] yetAnotherArray = new String[] {"A""E""Z""B""C"};
Arrays.sort(yetAnotherArray, 13,
                Comparator.comparing(String::toString).reversed());

只對 1-3 位置上的元素進行反序,所以結果如下所示:

[A, Z, E, B, C]

08、數組搜索

有時候,我們需要從數組中查找某個具體的元素,最直接的方式就是通過遍歷的方式:

int[] anArray = new int[] {52148};
for (int i = 0; i < anArray.length; i++) {
    if (anArray[i] == 4) {
        System.out.println("找到了 " + i);
        break;
    }
}

上例中從數組中查詢元素 4,找到后通過 break 關鍵字退出循環。

如果數組提前進行了排序,就可以使用二分查找法,這樣效率就會更高一些。Arrays.binarySearch() 方法可供我們使用,它需要傳遞一個數組,和要查找的元素。

int[] anArray = new int[] {12345};
int index = Arrays.binarySearch(anArray, 4);

09、總結

除了一維數組,還有二維數組,但說實話,二維數組不太常用,這裏就不再介紹了,感興趣的話,可以嘗試打印以下楊輝三角。

這篇文章,我們介紹了 Java 數組的基本用法和一些高級用法,我想小夥伴們應該已經完全掌握了。

我是沉默王二,一枚有趣的程序員。如果覺得文章對你有點幫助,請微信搜索「 沉默王二 」第一時間閱讀。

本文 GitHub 已經收錄,有大廠面試完整考點,歡迎 Star。

原創不易,莫要白票,請你為本文點個贊吧,這將是我寫作更多優質文章的最強動力。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

※教你寫出一流的銷售文案?

※超省錢租車方案

這一次搞懂SpringBoot核心原理(自動配置、事件驅動、Condition)

@

目錄

  • 前言
  • 正文
    • 啟動原理
    • 事件驅動
    • 自動配置原理
    • Condition註解原理
  • 總結

前言

SpringBoot是Spring的包裝,通過自動配置使得SpringBoot可以做到開箱即用,上手成本非常低,但是學習其實現原理的成本大大增加,需要先了解熟悉Spring原理。如果還不清楚Spring原理的,可以先查看博主之前的文章,本篇主要分析SpringBoot的啟動、自動配置、Condition、事件驅動原理。

正文

啟動原理

SpringBoot啟動非常簡單,因其內置了Tomcat,所以只需要通過下面幾種方式啟動即可:

@SpringBootApplication(scanBasePackages = {"cn.dark"})
public class SpringbootDemo {

    public static void main(String[] args) {
    	// 第一種
        SpringApplication.run(SpringbootDemo .class, args);

		// 第二種
        new SpringApplicationBuilder(SpringbootDemo .class)).run(args);

		// 第三種
        SpringApplication springApplication = new SpringApplication(SpringbootDemo.class);
        springApplication.run();		
    }
}

可以看到第一種是最簡單的,也是最常用的方式,需要注意類上面需要標註@SpringBootApplication註解,這是自動配置的核心實現,稍後分析,先來看看SpringBoot啟動做了些什麼?
在往下之前,不妨先猜測一下,run方法中需要做什麼?對比Spring源碼,我們知道,Spring的啟動都會創建一個ApplicationContext的應用上下文對象,並調用其refresh方法啟動容器,SpringBoot只是Spring的一層殼,肯定也避免不了這樣的操作。另一方面,以前通過Spring搭建的項目,都需要打成War包發布到Tomcat才行,而現在SpringBoot已經內置了Tomcat,只需要打成Jar包啟動即可,所以在run方法中肯定也會創建對應的Tomcat對象並啟動。以上只是我們的猜想,下面就來驗證,進入run方法:

	public ConfigurableApplicationContext run(String... args) {
		// 統計時間用的工具類
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		// 獲取實現了SpringApplicationRunListener接口的實現類,通過SPI機制加載
		// META-INF/spring.factories文件下的類
		SpringApplicationRunListeners listeners = getRunListeners(args);

		// 首先調用SpringApplicationRunListener的starting方法
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);

			// 處理配置數據
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);

			// 啟動時打印banner
			Banner printedBanner = printBanner(environment);

			// 創建上下文對象
			context = createApplicationContext();

			// 獲取SpringBootExceptionReporter接口的類,異常報告
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);

			prepareContext(context, environment, listeners, applicationArguments, printedBanner);

			// 核心方法,啟動spring容器
			refreshContext(context);
			afterRefresh(context, applicationArguments);

			// 統計結束
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			// 調用started
			listeners.started(context);

			// ApplicationRunner
			// CommandLineRunner
			// 獲取這兩個接口的實現類,並調用其run方法
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			// 最後調用running方法
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

SpringBoot的啟動流程就是這個方法,先看getRunListeners方法,這個方法就是去拿到所有的SpringApplicationRunListener實現類,這些類是用於SpringBoot事件發布的,關於事件驅動稍後分析,這裏主要看這個方法的實現原理:

	private SpringApplicationRunListeners getRunListeners(String[] args) {
		Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
		return new SpringApplicationRunListeners(logger,
				getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
	}

	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		// 加載上來后反射實例化
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

	public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
		String factoryTypeName = factoryType.getName();
		return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
	}

	public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

	private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
		MultiValueMap<String, String> result = cache.get(classLoader);
		if (result != null) {
			return result;
		}

		try {
			Enumeration<URL> urls = (classLoader != null ?
					classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
			result = new LinkedMultiValueMap<>();
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				UrlResource resource = new UrlResource(url);
				Properties properties = PropertiesLoaderUtils.loadProperties(resource);
				for (Map.Entry<?, ?> entry : properties.entrySet()) {
					String factoryTypeName = ((String) entry.getKey()).trim();
					for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
						result.add(factoryTypeName, factoryImplementationName.trim());
					}
				}
			}
			cache.put(classLoader, result);
			return result;
		}
	}

一步步追蹤下去可以看到最終就是通過SPI機制根據接口類型從META-INF/spring.factories文件中加載對應的實現類並實例化,SpringBoot的自動配置也是這樣實現的。為什麼要這樣實現呢?通過註解掃描不可以么?當然不行,這些類都在第三方jar包中,註解掃描實現是很麻煩的,當然你也可以通過@Import註解導入,但是這種方式不適合擴展類特別多的情況,所以這裏採用SPI的優點就顯而易見了。
回到run方法中,可以看到調用了createApplicationContext方法,見名知意,這個就是去創建應用上下文對象:

	public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
			+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";

	protected ConfigurableApplicationContext createApplicationContext() {
		Class<?> contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				switch (this.webApplicationType) {
				case SERVLET:
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
			}
		}
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

注意這裏通過反射實例化了一個新的沒見過的上下文對象AnnotationConfigServletWebServerApplicationContext,這個是SpringBoot擴展的,看看其構造方法:

	public AnnotationConfigServletWebServerApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

如果你有看過Spring註解驅動的實現原理,這兩個對象肯定不會陌生,一個實支持註解解析的,另外一個是掃描包用的。
上下文創建好了,下一步自然就是調用refresh方法啟動容器:


	private void refreshContext(ConfigurableApplicationContext context) {
		refresh(context);
		if (this.registerShutdownHook) {
			try {
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
	}

	protected void refresh(ApplicationContext applicationContext) {
		Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
		((AbstractApplicationContext) applicationContext).refresh();
	}

這裏首先會調用到其父類中ServletWebServerApplicationContext

	public final void refresh() throws BeansException, IllegalStateException {
		try {
			super.refresh();
		}
		catch (RuntimeException ex) {
			stopAndReleaseWebServer();
			throw ex;
		}
	}

可以看到是直接委託給了父類:

	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

這個方法不會陌生吧,之前已經分析過了,這裏不再贅述,至此SpringBoot的容器就啟動了,但是Tomcat啟動是在哪裡呢?run方法中也沒有看到。實際上Tomcat的啟動也是在refresh流程中,這個方法其中一步是調用了onRefresh方法,在Spring中這是一個沒有實現的模板方法,而SpringBoot就通過這個方法完成了Tomcat的啟動:

	protected void onRefresh() {
		super.onRefresh();
		try {
			createWebServer();
		}
		catch (Throwable ex) {
			throw new ApplicationContextException("Unable to start web server", ex);
		}
	}

	private void createWebServer() {
		WebServer webServer = this.webServer;
		ServletContext servletContext = getServletContext();
		if (webServer == null && servletContext == null) {
			ServletWebServerFactory factory = getWebServerFactory();
			// 主要看這個方法
			this.webServer = factory.getWebServer(getSelfInitializer());
		}
		else if (servletContext != null) {
			try {
				getSelfInitializer().onStartup(servletContext);
			}
			catch (ServletException ex) {
				throw new ApplicationContextException("Cannot initialize servlet context", ex);
			}
		}
		initPropertySources();
	}

這裏首先拿到TomcatServletWebServerFactory對象,通過該對象再去創建和啟動Tomcat:

	public WebServer getWebServer(ServletContextInitializer... initializers) {
		if (this.disableMBeanRegistry) {
			Registry.disableRegistry();
		}
		Tomcat tomcat = new Tomcat();
		File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
		tomcat.setBaseDir(baseDir.getAbsolutePath());
		Connector connector = new Connector(this.protocol);
		connector.setThrowOnFailure(true);
		tomcat.getService().addConnector(connector);
		customizeConnector(connector);
		tomcat.setConnector(connector);
		tomcat.getHost().setAutoDeploy(false);
		configureEngine(tomcat.getEngine());
		for (Connector additionalConnector : this.additionalTomcatConnectors) {
			tomcat.getService().addConnector(additionalConnector);
		}
		prepareContext(tomcat.getHost(), initializers);
		return getTomcatWebServer(tomcat);
	}

上面的每一步都可以對比Tomcat的配置文件,需要注意默認只支持了http協議:

	Connector connector = new Connector(this.protocol);

	private String protocol = DEFAULT_PROTOCOL;
	public static final String DEFAULT_PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";

如果想要擴展的話則可以對additionalTomcatConnectors屬性設置值,需要注意這個屬性沒有對應的setter方法,只有addAdditionalTomcatConnectors方法,也就是說我們只能通過實現BeanFactoryPostProcessor接口的postProcessBeanFactory方法,而不能通過BeanDefinitionRegistryPostProcessorpostProcessBeanDefinitionRegistry方法,因為前者可以通過傳入的BeanFactory對象提前獲取到TomcatServletWebServerFactory對象調用addAdditionalTomcatConnectors即可;而後者只能拿到BeanDefinition對象,該對象只能通過setter方法設置值。

事件驅動

Spring原本就提供了事件機制,而在SpringBoot中又對其進行擴展,通過發布訂閱事件在容器的整個生命周期的不同階段進行不同的操作。我們先來看看SpringBoot啟動關閉的過程中默認會發布哪些事件,使用下面的代碼即可:

@SpringBootApplication
public class SpringEventDemo {

    public static void main(String[] args) {
        new SpringApplicationBuilder(SpringEventDemo.class)
                .listeners(event -> {
                    System.err.println("接收到事件:" + event.getClass().getSimpleName());
                })
                .run()
                .close();
    }

}

這段代碼會在控制台打印所有的事件名稱,按照順序如下:

  • ApplicationStartingEvent:容器啟動
  • ApplicationEnvironmentPreparedEvent:環境準備好
  • ApplicationContextInitializedEvent:上下文初始化完成
  • ApplicationPreparedEvent:上下文準備好
  • ContextRefreshedEvent:上下文刷新完
  • ServletWebServerInitializedEvent:webServer初始化完成
  • ApplicationStartedEvent:容器啟動完成
  • ApplicationReadyEvent:容器就緒
  • ContextClosedEvent:容器關閉

以上是正常啟動關閉,如果發生異常還有發布ApplicationFailedEvent事件。事件的發布遍布在整個容器的啟動關閉周期中,事件發布對象剛剛我們也看到了是通過SPI加載的SpringApplicationRunListener實現類EventPublishingRunListener,同樣事件監聽器也是在spring.factories文件中配置的,默認實現了以下監聽器:

org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

可以看到有用於文件編碼的(FileEncodingApplicationListener),有加載日誌框架的(LoggingApplicationListener),還有加載配置的(ConfigFileApplicationListener)等等一系列監聽器,SpringBoot也就是通過這系列監聽器將必要的配置和組件加載到容器中來,這裏不再詳細分析,感興趣的讀者可以通過其實現的onApplicationEvent方法看到每個監聽器究竟是監聽的哪一個事件,當然事件發布和監聽我們自己也是可以擴展的。

自動配置原理

SpringBoot最核心的還是自動配置,為什麼它能做到開箱即用,不再需要我們手動使用@EnableXXX等註解來開啟?這一切的答案就在@SpringBootApplication註解中:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}

這裏重要的註解有三個:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。@ComponentScan就不用再說了,@SpringBootConfiguration等同於@Configuration,而@EnableAutoConfiguration就是開啟自動配置:

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

}

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

@AutoConfigurationPackage註解的作用就是將該註解所標記類所在的包作為自動配置的包,簡單看看就行,主要看AutoConfigurationImportSelector,這個就是實現自動配置的核心類,注意這個類是實現的DeferredImportSelector接口。
在這個類中有一個selectImports方法。這個方法在我之前的文章這一次搞懂Spring事務註解的解析也有分析過,只是實現類不同,它同樣會被ConfigurationClassPostProcessor類調用,先來看這個方法做了些什麼:

	public String[] selectImports(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return NO_IMPORTS;
		}
		AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
				.loadMetadata(this.beanClassLoader);
		// 獲取所有的自動配置類
		AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
				annotationMetadata);
		return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
	}

	protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
			AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		// SPI獲取EnableAutoConfiguration為key的所有實現類
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		// 把某些自動配置類過濾掉
		configurations = filter(configurations, autoConfigurationMetadata);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		// 包裝成自動配置實體類
		return new AutoConfigurationEntry(configurations, exclusions);
	}

	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		// SPI獲取EnableAutoConfiguration為key的所有實現類
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

追蹤源碼最終可以看到也是從META-INF/spring.factories文件中拿到所有EnableAutoConfiguration對應的值(在spring-boot-autoconfigure中)並通過反射實例化,過濾后包裝成AutoConfigurationEntry對象返回。
看到這裏你應該會覺得自動配置的實現就是通過這個selectImports方法,但實際上這個方法通常並不會被調用到,而是會調用該類的內部類AutoConfigurationGroupprocessselectImports方法,前者同樣是通過getAutoConfigurationEntry拿到所有的自動配置類,而後者這是過濾排序並包裝后返回。
下面就來分析ConfigurationClassPostProcessor是怎麼調用到這裏的,直接進入processConfigBeanDefinitions方法:

	public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		String[] candidateNames = registry.getBeanDefinitionNames();

		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// Return immediately if no @Configuration classes were found
		if (configCandidates.isEmpty()) {
			return;
		}

		// Sort by previously determined @Order value, if applicable
		configCandidates.sort((bd1, bd2) -> {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return Integer.compare(i1, i2);
		});

		// Detect any custom bean name generation strategy supplied through the enclosing application context
		SingletonBeanRegistry sbr = null;
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
						AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
				if (generator != null) {
					this.componentScanBeanNameGenerator = generator;
					this.importBeanNameGenerator = generator;
				}
			}
		}

		if (this.environment == null) {
			this.environment = new StandardEnvironment();
		}

		// Parse each @Configuration class
		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			parser.parse(candidates);
			parser.validate();

			Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
			configClasses.removeAll(alreadyParsed);

			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
						registry, this.sourceExtractor, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
			this.reader.loadBeanDefinitions(configClasses);
			alreadyParsed.addAll(configClasses);

			// 省略。。。。
	}

前面一大段主要是拿到合格的Configuration配置類,主要邏輯是在ConfigurationClassParser.parse方法中,該方法完成了對@Component、@Bean、@Import、@ComponentScans等註解的解析,這裏主要看對@Import的解析,其它的讀者可自行分析。一步步追蹤,最終會進入到processConfigurationClass方法:

	protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}

		ConfigurationClass existingClass = this.configurationClasses.get(configClass);
		if (existingClass != null) {
			if (configClass.isImported()) {
				if (existingClass.isImported()) {
					existingClass.mergeImportedBy(configClass);
				}
				// Otherwise ignore new imported config class; existing non-imported class overrides it.
				return;
			}
			else {
				// Explicit bean definition found, probably replacing an import.
				// Let's remove the old one and go with the new one.
				this.configurationClasses.remove(configClass);
				this.knownSuperclasses.values().removeIf(configClass::equals);
			}
		}

		// Recursively process the configuration class and its superclass hierarchy.
		SourceClass sourceClass = asSourceClass(configClass);
		do {
			sourceClass = doProcessConfigurationClass(configClass, sourceClass);
		}
		while (sourceClass != null);

		this.configurationClasses.put(configClass, configClass);
	}

這裏需要注意this.conditionEvaluator.shouldSkip方法的調用,這個方法就是進行Bean加載過濾的,即根據@Condition註解的匹配值判斷是否加載該Bean,具體實現稍後分析,繼續跟蹤主流程doProcessConfigurationClass

	protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
			throws IOException {
		省略....

		// Process any @Import annotations
		processImports(configClass, sourceClass, getImports(sourceClass), true);

		省略....
		return null;
	}

這裏就是完成對一系列註解的支撐,我省略掉了,主要看processImports方法,這個方法就是處理@Import註解的:

	private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, boolean checkForCircularImports) {

		if (importCandidates.isEmpty()) {
			return;
		}

		if (checkForCircularImports && isChainedImportOnStack(configClass)) {
			this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
		}
		else {
			this.importStack.push(configClass);
			try {
				for (SourceClass candidate : importCandidates) {
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						Class<?> candidateClass = candidate.loadClass();
						ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
								this.environment, this.resourceLoader, this.registry);
						if (selector instanceof DeferredImportSelector) {
							this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
						}
						else {
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
							processImports(configClass, currentSourceClass, importSourceClasses, false);
						}
					}
					else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
						Class<?> candidateClass = candidate.loadClass();
						ImportBeanDefinitionRegistrar registrar =
								ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
										this.environment, this.resourceLoader, this.registry);
						configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
					}
					else {
						this.importStack.registerImport(
								currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
						processConfigurationClass(candidate.asConfigClass(configClass));
					}
				}
			}
		}
	}

剛剛我提醒過AutoConfigurationImportSelector是實現DeferredImportSelector接口的,如果不是該接口的實現類則是直接調用selectImports方法,反之則是調用DeferredImportSelectorHandler.handle方法:

		private List<DeferredImportSelectorHolder> deferredImportSelectors = new ArrayList<>();
		
		public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
			DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(
					configClass, importSelector);
			if (this.deferredImportSelectors == null) {
				DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
				handler.register(holder);
				handler.processGroupImports();
			}
			else {
				this.deferredImportSelectors.add(holder);
			}
		}

首先創建了一個DeferredImportSelectorHolder對象,如果是第一次執行則是添加到deferredImportSelectors屬性中,等到ConfigurationClassParser.parse的最後調用process方法:

	public void parse(Set<BeanDefinitionHolder> configCandidates) {
		省略.....

		this.deferredImportSelectorHandler.process();
	}

	public void process() {
		List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
		this.deferredImportSelectors = null;
		try {
			if (deferredImports != null) {
				DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
				deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
				deferredImports.forEach(handler::register);
				handler.processGroupImports();
			}
		}
		finally {
			this.deferredImportSelectors = new ArrayList<>();
		}
	}

反之則是直接執行,首先通過register拿到AutoConfigurationGroup對象:

	public void register(DeferredImportSelectorHolder deferredImport) {
		Class<? extends Group> group = deferredImport.getImportSelector()
				.getImportGroup();
		DeferredImportSelectorGrouping grouping = this.groupings.computeIfAbsent(
				(group != null ? group : deferredImport),
				key -> new DeferredImportSelectorGrouping(createGroup(group)));
		grouping.add(deferredImport);
		this.configurationClasses.put(deferredImport.getConfigurationClass().getMetadata(),
				deferredImport.getConfigurationClass());
	}

	public Class<? extends Group> getImportGroup() {
		return AutoConfigurationGroup.class;
	}

然後在processGroupImports方法中進行真正的處理:

		public void processGroupImports() {
			for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
				grouping.getImports().forEach(entry -> {
					ConfigurationClass configurationClass = this.configurationClasses.get(
							entry.getMetadata());
					try {
						processImports(configurationClass, asSourceClass(configurationClass),
								asSourceClasses(entry.getImportClassName()), false);
					}
					catch (BeanDefinitionStoreException ex) {
						throw ex;
					}
					catch (Throwable ex) {
						throw new BeanDefinitionStoreException(
								"Failed to process import candidates for configuration class [" +
										configurationClass.getMetadata().getClassName() + "]", ex);
					}
				});
			}
		}

		public Iterable<Group.Entry> getImports() {
			for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
				this.group.process(deferredImport.getConfigurationClass().getMetadata(),
						deferredImport.getImportSelector());
			}
			return this.group.selectImports();
		}

getImports方法中就完成了對processselectImports方法的調用,拿到自動配置類后再遞歸調用調用processImports方法完成對自動配置類的加載。至此,自動配置的加載過程就分析完了,下面是時序圖:

Condition註解原理

在自動配置類中有很多Condition相關的註解,以AOP為例:

Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(Advice.class)
	static class AspectJAutoProxyingConfiguration {

		@Configuration(proxyBeanMethods = false)
		@EnableAspectJAutoProxy(proxyTargetClass = false)
		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
				matchIfMissing = false)
		static class JdkDynamicAutoProxyConfiguration {

		}

		@Configuration(proxyBeanMethods = false)
		@EnableAspectJAutoProxy(proxyTargetClass = true)
		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
				matchIfMissing = true)
		static class CglibAutoProxyConfiguration {

		}

	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingClass("org.aspectj.weaver.Advice")
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
			matchIfMissing = true)
	static class ClassProxyingConfiguration {

		ClassProxyingConfiguration(BeanFactory beanFactory) {
			if (beanFactory instanceof BeanDefinitionRegistry) {
				BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
				AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
		}

	}

}

這裏就能看到@ConditionalOnProperty、@ConditionalOnClass、@ConditionalOnMissingClass,另外還有@ConditionalOnBean、@ConditionalOnMissingBean等等很多條件匹配註解。這些註解表示條件匹配才會加載該Bean,以@ConditionalOnProperty為例,表明配置文件中符合條件才會加載對應的Bean,prefix表示在配置文件中的前綴,name表示配置的名稱,havingValue表示配置為該值時才匹配,matchIfMissing則是表示沒有該配置是否默認加載對應的Bean。其它註解可類比理解記憶,下面主要來分析該註解的實現原理。
這裏註解點進去看會發現每個註解上都標註了@Conditional註解,並且value值都對應一個類,比如OnBeanCondition,而這些類都實現了Condition接口,看看其繼承體系:

上面只展示了幾個實現類,但實際上Condition的實現類是非常多的,我們還可以自己實現該接口來擴展@Condition註解。
Condition接口中有一個matches方法,這個方法返回true則表示匹配。該方法在ConfigurationClassParser中多處都有調用,也就是剛剛我提醒過的shouldSkip方法,具體實現是在ConditionEvaluator類中:

	public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
		if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
			return false;
		}

		if (phase == null) {
			if (metadata instanceof AnnotationMetadata &&
					ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
				return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
			}
			return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
		}

		List<Condition> conditions = new ArrayList<>();
		for (String[] conditionClasses : getConditionClasses(metadata)) {
			for (String conditionClass : conditionClasses) {
				Condition condition = getCondition(conditionClass, this.context.getClassLoader());
				conditions.add(condition);
			}
		}

		AnnotationAwareOrderComparator.sort(conditions);

		for (Condition condition : conditions) {
			ConfigurationPhase requiredPhase = null;
			if (condition instanceof ConfigurationCondition) {
				requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
			}
			if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
				return true;
			}
		}

		return false;
	}

再來看看matches的實現,但OnBeanCondition類中沒有實現該方法,而是在其父類SpringBootCondition中:

	public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		String classOrMethodName = getClassOrMethodName(metadata);
		try {
			ConditionOutcome outcome = getMatchOutcome(context, metadata);
			logOutcome(classOrMethodName, outcome);
			recordEvaluation(context, classOrMethodName, outcome);
			return outcome.isMatch();
		}

getMatchOutcome方法也是一個模板方法,具體的匹配邏輯就在這個方法中實現,該方法返回的ConditionOutcome對象就包含了是否匹配日誌消息兩個字段。進入到OnBeanCondition類中:

	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		ConditionMessage matchMessage = ConditionMessage.empty();
		MergedAnnotations annotations = metadata.getAnnotations();
		if (annotations.isPresent(ConditionalOnBean.class)) {
			Spec<ConditionalOnBean> spec = new Spec<>(context, metadata, annotations, ConditionalOnBean.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (!matchResult.isAllMatched()) {
				String reason = createOnBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(spec.message().because(reason));
			}
			matchMessage = spec.message(matchMessage).found("bean", "beans").items(Style.QUOTE,
					matchResult.getNamesOfAllMatches());
		}
		if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
			Spec<ConditionalOnSingleCandidate> spec = new SingleCandidateSpec(context, metadata, annotations);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (!matchResult.isAllMatched()) {
				return ConditionOutcome.noMatch(spec.message().didNotFind("any beans").atAll());
			}
			else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matchResult.getNamesOfAllMatches(),
					spec.getStrategy() == SearchStrategy.ALL)) {
				return ConditionOutcome.noMatch(spec.message().didNotFind("a primary bean from beans")
						.items(Style.QUOTE, matchResult.getNamesOfAllMatches()));
			}
			matchMessage = spec.message(matchMessage).found("a primary bean from beans").items(Style.QUOTE,
					matchResult.getNamesOfAllMatches());
		}
		if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
			Spec<ConditionalOnMissingBean> spec = new Spec<>(context, metadata, annotations,
					ConditionalOnMissingBean.class);
			MatchResult matchResult = getMatchingBeans(context, spec);
			if (matchResult.isAnyMatched()) {
				String reason = createOnMissingBeanNoMatchReason(matchResult);
				return ConditionOutcome.noMatch(spec.message().because(reason));
			}
			matchMessage = spec.message(matchMessage).didNotFind("any beans").atAll();
		}
		return ConditionOutcome.match(matchMessage);
	}

可以看到該類支持了@ConditionalOnBean、@ConditionalOnSingleCandidate、@ConditionalOnMissingBean註解,主要的匹配邏輯在getMatchingBeans方法中:

	protected final MatchResult getMatchingBeans(ConditionContext context, Spec<?> spec) {
		ClassLoader classLoader = context.getClassLoader();
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		boolean considerHierarchy = spec.getStrategy() != SearchStrategy.CURRENT;
		Set<Class<?>> parameterizedContainers = spec.getParameterizedContainers();
		if (spec.getStrategy() == SearchStrategy.ANCESTORS) {
			BeanFactory parent = beanFactory.getParentBeanFactory();
			Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
					"Unable to use SearchStrategy.ANCESTORS");
			beanFactory = (ConfigurableListableBeanFactory) parent;
		}
		MatchResult result = new MatchResult();
		Set<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(classLoader, beanFactory, considerHierarchy,
				spec.getIgnoredTypes(), parameterizedContainers);
		for (String type : spec.getTypes()) {
			Collection<String> typeMatches = getBeanNamesForType(classLoader, considerHierarchy, beanFactory, type,
					parameterizedContainers);
			typeMatches.removeAll(beansIgnoredByType);
			if (typeMatches.isEmpty()) {
				result.recordUnmatchedType(type);
			}
			else {
				result.recordMatchedType(type, typeMatches);
			}
		}
		for (String annotation : spec.getAnnotations()) {
			Set<String> annotationMatches = getBeanNamesForAnnotation(classLoader, beanFactory, annotation,
					considerHierarchy);
			annotationMatches.removeAll(beansIgnoredByType);
			if (annotationMatches.isEmpty()) {
				result.recordUnmatchedAnnotation(annotation);
			}
			else {
				result.recordMatchedAnnotation(annotation, annotationMatches);
			}
		}
		for (String beanName : spec.getNames()) {
			if (!beansIgnoredByType.contains(beanName) && containsBean(beanFactory, beanName, considerHierarchy)) {
				result.recordMatchedName(beanName);
			}
			else {
				result.recordUnmatchedName(beanName);
			}
		}
		return result;
	}

這裏邏輯看起來比較複雜,但實際上就做了兩件事,首先通過getNamesOfBeansIgnoredByType方法調用beanFactory.getBeanNamesForType拿到容器中對應的Bean實例,然後根據返回的結果判斷哪些Bean存在,哪些Bean不存在(Condition註解中是可以配置多個值的)並返回MatchResult對象,而MatchResult中只要有一個Bean沒有匹配上就返回false,也就決定了當前Bean是否需要實例化。

總結

本篇分析了SpringBoot核心原理的實現,通過本篇相信讀者也將能更加熟練地使用和擴展SpringBoot。另外還有一些常用的組件我沒有展開分析,如事務、MVC、監聽器的自動配置,這些我們有了Spring源碼基礎的話下來看一下就明白了,這裏就不贅述了。最後讀者可以思考一下我們應該如何自定義starter啟動器,相信看完本篇應該難不倒你。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※超省錢租車方案

強迫餵食太殘忍 紐約市2022年起禁售鵝肝

摘錄自2019年10月31日中央社報導

紐約市議會31日以以42票贊成、6票反對的壓倒性票數,通過將從2022年起禁售鵝肝。 議員認為,為滿足人類口腹之慾而逼迫鴨鵝將肝臟養肥,是很殘忍的事。

這項法律將自2022年10月起生效,禁止任何組織銷售、提供甚至是處理鵝肝。 違者每次違規將被罰500到2000美元。

 不過,鵝肝農民大喊不公,揚言將採取法律行動。農民聲稱他們的生產作業並不殘忍,是運動人士誇大了動物承受的苦難。 他們說,他們餵食鴨鵝的玉米量,並未超過牠們自己食用的量。

全球目前已有數國禁止生產鵝肝,包括英國等。鵝肝產業正在探索替代方法,尋找不需利用強迫餵食手段生產鵝肝的辦法。

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家公司費用,距離,噸數怎麼算?達人教你簡易估價知識!

※教你寫出一流的銷售文案?

※超省錢租車方案

冰淇淋豆 亞馬遜雨林的「綠金」新希望

環境資訊中心綜合外電;姜唯 編譯;林大利 審校

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

新北清潔公司,居家、辦公、裝潢細清專業服務

※別再煩惱如何寫文案,掌握八大原則!

※教你寫出一流的銷售文案?

※超省錢租車方案