主頁 > 後端開發 > 專案里出現兩個配置類繼承WebMvcConfigurationSupport時,為什么只有一個會生效(原始碼分析)

專案里出現兩個配置類繼承WebMvcConfigurationSupport時,為什么只有一個會生效(原始碼分析)

2020-09-29 17:02:09 後端開發

  為什么我們的專案里出現兩個配置類繼承WebMvcConfigurationSupport時,只有一個會生效,我在網上找了半天都是說結果的,沒有人分析原始碼到底是為啥,博主準備講解一下,希望可以幫到大家!

  大家基本遇到過一種情況,就是我配置類中已經配置了,為什么就是沒有生效呢?其中一種原因就是,自己寫的配置類也繼承了WebMvcConfigurationSupport,當專案出現兩個配置類都繼承該類時,只會講第一個配置類生效,至于為什么,就是今天博主需要講解的,我們必須了解一些springboot的bean的創建程序也就是其生命周期:

  https://www.processon.com/view/link/5f704050f346fb166d0f3e3c

  雖然畫的比較簡單,有許多細節都沒有決議,但是對于當前我們的話題來講已經基本可以了;

  第一步:我們的配置類是從哪里開始創建決議的:大家可以看到圖示bean的流程中doProcessConfigurationClass(configClass, sourceClass, filter);方法,我們看一下是如何呼叫它 的:

 1  protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
 2         if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
 3             return;
 4         }
 5 
 6         ConfigurationClass existingClass = this.configurationClasses.get(configClass);
 7         if (existingClass != null) {
 8             if (configClass.isImported()) {
 9                 if (existingClass.isImported()) {
10                     existingClass.mergeImportedBy(configClass);
11                 }
12                 // Otherwise ignore new imported config class; existing non-imported class overrides it.
13                 return;
14             }
15             else {
16                 // Explicit bean definition found, probably replacing an import.
17                 // Let's remove the old one and go with the new one.
18                 this.configurationClasses.remove(configClass);
19                 this.knownSuperclasses.values().removeIf(configClass::equals);
20             }
21         }
22 
23         // Recursively process the configuration class and its superclass hierarchy.
24         SourceClass sourceClass = asSourceClass(configClass, filter);
25         do {
26             //從這里開始決議我們的當前配置類
27             sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
28         }
29         while (sourceClass != null);
30 
31         this.configurationClasses.put(configClass, configClass);
32     }

 

  這里可以看到一個while回圈,為什么要這么設計呢?我們再看看doProcessConfigurationClass(configClass, sourceClass, filter);方法的原始碼

 1 protected final SourceClass doProcessConfigurationClass(
 2             ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
 3             throws IOException {
 4 
 5         if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
 6             // Recursively process any member (nested) classes first
 7             processMemberClasses(configClass, sourceClass, filter);
 8         }
 9 
10         // Process any @PropertySource annotations
11         for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
12                 sourceClass.getMetadata(), PropertySources.class,
13                 org.springframework.context.annotation.PropertySource.class)) {
14             if (this.environment instanceof ConfigurableEnvironment) {
15                 processPropertySource(propertySource);
16             }
17             else {
18                 logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
19                         "]. Reason: Environment must implement ConfigurableEnvironment");
20             }
21         }
22 
23         // Process any @ComponentScan annotations
24         Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
25                 sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
26         if (!componentScans.isEmpty() &&
27                 !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
28             for (AnnotationAttributes componentScan : componentScans) {
29                 // The config class is annotated with @ComponentScan -> perform the scan immediately
30                 Set<BeanDefinitionHolder> scannedBeanDefinitions =
31                         this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
32                 // Check the set of scanned definitions for any further config classes and parse recursively if needed
33                 for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
34                     BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
35                     if (bdCand == null) {
36                         bdCand = holder.getBeanDefinition();
37                     }
38                     if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
39                         parse(bdCand.getBeanClassName(), holder.getBeanName());
40                     }
41                 }
42             }
43         }
44 
45         // Process any @Import annotations
46         processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
47 
48         // Process any @ImportResource annotations
49         AnnotationAttributes importResource =
50                 AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
51         if (importResource != null) {
52             String[] resources = importResource.getStringArray("locations");
53             Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
54             for (String resource : resources) {
55                 String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
56                 configClass.addImportedResource(resolvedResource, readerClass);
57             }
58         }
59         //這里也很重要,這里開始會決議當前配置類里的bean,然后決議父類里面的bean,就是這里才會把WebMvcConfigurationSupport的所有bean
60         //都決議出來并添加到configClass里面,不管決議當前類還是父類,configClass都是自己當前的配置類,所以WebMvcConfigurationSupport
61         // Process individual @Bean methods
62         Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
63         for (MethodMetadata methodMetadata : beanMethods) {
64             configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
65         }
66 
67         // Process default methods on interfaces
68         processInterfaces(configClass, sourceClass);
69 
70         //最主要的就是這里,決議當前類的父類
71         // Process superclass, if any
72         if (sourceClass.getMetadata().hasSuperClass()) {
73             String superclass = sourceClass.getMetadata().getSuperClassName();
74             if (superclass != null && !superclass.startsWith("java") &&
75                     !this.knownSuperclasses.containsKey(superclass)) {
76                 //如果我們第一個繼承了WebMvcConfigurationSupport的配置類,已經被掃描到,就會添加一個map快取,
77                 //下一個也繼承了WebMvcConfigurationSupport的配置類,將不在決議,直接回傳null,結束回圈,這也是外面一層為什么要添加while回圈
78                 this.knownSuperclasses.put(superclass, configClass);
79                 // Superclass found, return its annotation metadata and recurse
80                 return sourceClass.getSuperClass();
81             }
82         }
83 
84         // No superclass -> processing is complete
85         return null;

  所以就現在來講,基本已經決定了,決議第一個配置類的時候,第二個配置類重寫的任何方法基本沒什么用了,因為父類所有的bean已經在第一個配置類中決議掃描到了,就剩下如何去創建bean了,我們再繼續往下看會更明白;

  第二步:現在當所有bean已經掃描到,并且bean定義已經完成,該開始實體化了,看一下createBeanInstance的創建程序,最后生成的時候會找到 factoryBean也就是我們自己的配置類

 1 private Object instantiate(String beanName, RootBeanDefinition mbd,
 2             @Nullable Object factoryBean, Method factoryMethod, Object[] args) {
 3 
 4         try {
 5             if (System.getSecurityManager() != null) {
 6                 return AccessController.doPrivileged((PrivilegedAction<Object>) () ->
 7                         this.beanFactory.getInstantiationStrategy().instantiate(
 8                                 mbd, beanName, this.beanFactory, factoryBean, factoryMethod, args),
 9                         this.beanFactory.getAccessControlContext());
10             }
11             else {
12                 return this.beanFactory.getInstantiationStrategy().instantiate(
13                         mbd, beanName, this.beanFactory, factoryBean, factoryMethod, args);
14             }
15         }
16         catch (Throwable ex) {
17             throw new BeanCreationException(mbd.getResourceDescription(), beanName,
18                     "Bean instantiation via factory method failed", ex);
19         }
20     }

  其中factoryBean就是我們的當前第一個被決議到的配置類bean,截圖為證,我自己寫了兩個配置類,第一個被加載的是MyASD,瞎寫的名,好區分,第二個配置類是WebConfiguration,我們只看WebMvcConfigurationSupport里面的其中一個bean的創建程序,就是requestMappingHandlerAdapter,為啥要看這個,正好跟上節json自定義銜接,

https://www.cnblogs.com/guoxiaoyu/p/13667961.html

 

 

 

   到這里,我們可以看到在生成requestMappingHandlerAdapter時,呼叫extendMessageConverters方法時,一定會呼叫第一個配置類中的重寫方法,因為所有的WebMvcConfigurationSupport里面 bean都被第一個配置類決議完了,所有的factoryBean都是當前第一個配置類,就算第二個配置完沒有報錯,也不會生效了,

  我直接把這個問題用原始碼的方式講解清楚,方便大家明白為什么配置兩個WebMvcConfigurationSupport類,只有一個生效,

 


轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/139125.html

標籤:Java

上一篇:華為20級技術官耗巨資整合2700頁TCP/IP網路協議精髓

下一篇:面試題精選:字串替換

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more