SpringBoot中@ComponentScan的使用詳解
SpringBoot @ComponentScan的使用
SpringBoot的啟動類中有一個@ComponentScan,之前項目由于這個注解造成打包失敗,這里對于這個注解進行總結(jié),防止下次遇到這個問題再被難住。
其實這個注解主要是針對于第三方j(luò)ar包中注解的應(yīng)用。
如果第三方包中沒有使用注解那么就完全不需要使用這個注解

使用方式如圖所示,這里掃描的是

maven項目的依賴包中的ins目錄下的組件
如果是直接引用項目

那么就要引用這個項目代碼的根路徑,一般公司會命名為“cn”
SpringBoot @ComponentScan 作用
SpringBoot在寫啟動類的時候如果不使用@ComponentScan指明對象掃描范圍,默認(rèn)指掃描當(dāng)前啟動類所在的包里的對象,如果當(dāng)前啟動類沒有包,則在啟動時會報錯:
Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package錯誤
因為啟動類不能直接放在main/java文件夾下,必須要建一個包把它放進去或者使用@ComponentScan指明要掃描的包。代碼示例如下:
@SpringBootApplication
@ComponentScan(basePackageClasses=MytestApplication.class)
public class MytestApplication {
public static void main(String[] args){
SpringApplication.run(MytestApplication.class, args);
}
}
@ComponentScan(basePackageClasses=要掃描類.class所在位置的包)-意思是要掃描哪個類所在的包
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis-Plus設(shè)置全局或者局部ID自增的實現(xiàn)
在使用Mybatis-Plus新增的時候,我們往往想要id隨著數(shù)據(jù)庫自增,本文主要介紹了Mybatis-Plus設(shè)置全局或者局部ID自增的實現(xiàn),具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
完美解決SpringCloud-OpenFeign使用okhttp替換不生效問題
這篇文章主要介紹了完美解決SpringCloud-OpenFeign使用okhttp替換不生效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02

