SpringBoot學習之包掃瞄

2021-10-24 15:28:05 字數 1287 閱讀 6196

帶著這樣乙個問題出發,為什麼需要將檔案放在啟動類所在包及子包才能被springboot自動掃瞄並註冊bean?

springboot會掃瞄啟動類所在包及子包的所有檔案,並將其註冊bean到容器中,應該是啟動時自動掃瞄,具體實現需要看原始碼。

package com.zrk.springboot;

public static void main(string args)

}

@target(elementtype.type)

@retention(retentionpolicy.runtime)

@documented

@inherited

@autoconfigurationpackage

@import(autoconfigurationimportselector.class)

public @inte***ce enableautoconfiguration

主要通過@import註解引入了autoconfigurationpackages.registrar.class

static class registrar implements importbeandefinitionregistrar, determinableimports 

...

可看出調了register(registry, new packageimport(metadata).getpackagename());方法

public static void register(beandefinitionregistry registry, string... packagenames) 

else

}

分析引數傳了beandefinitionregistry 變數,和一堆包名組成字串;最後一行呼叫registry.registerbeandefinition(bean, beandefinition)就是將包名下所有檔案掃瞄並將其下檔案分析並註冊bean,這樣就是大體流程,接下來除錯原始碼驗證一下。

此時 **new packageimport(metadata).getpackagename()**執行返回的值正好是主啟動類所在的包名com.zrk.springboot,進入register方法

證明了上述的分析

springBoot學習之註解小記

controller responsebody restcontroller 當方法或者類上增加了 responsebody註解時,所返回的引數為json格式。當沒有此註解時,引數會以鍵值對的形式傳入。data 提供該類所有屬性的getting和setting方法。cookievalue 用來獲取c...

SpringBoot 學習之Spring篇

scope 描述的是 spring 容器如何新建 bean 的例項的。spring 的scope 有以下幾種,通過 scope 註解來實現。1 singleton 乙個 spring 容器中只有乙個 bean 的例項,此為 spring的預設配置。2 prototype 每次呼叫新建乙個 bean ...

spring boot學習之熱部署

在pom檔案中加入devtools依賴即可,當classpath下的檔案發生了修改 儲存後 就會自動重啟專案 org.springframework.boot spring boot devtools true 當時我看書上就加了這段配置,然後我立馬啟動專案試了下,毫無疑問,沒有成功 idea中配置...