spring?boot自動(dòng)裝配之@ComponentScan注解用法詳解
1.@ComponentScan注解作用
@ComponentScan用于類或接口上主要是指定掃描路徑,spring會(huì)把指定路徑下帶有指定注解的類自動(dòng)裝配到bean容器里。會(huì)被自動(dòng)裝配的注解包括@Controller、@Service、@Component、@Repository等等。與ComponentScan注解相對(duì)應(yīng)的XML配置就是<context:component-scan/>, 根據(jù)指定的配置自動(dòng)掃描package,將符合條件的組件加入到IOC容器中;
XML的配置方式如下:
<context:component-scan base-package="com.example.test" use-default-filters="false"> <context:exclude-filter type="custom" expression="com.example.test.filter.MtyTypeFilter" /> </context:component-scan>
2. @ComponentScan注解屬性
@ComponentScan有如下常用屬性:
- basePackages和value:指定要掃描的路徑(package),如果為空則以@ComponentScan注解的類所在的包為基本的掃描路徑。
- basePackageClasses:指定具體掃描的類。
- includeFilters:指定滿足Filter條件的類。
- excludeFilters:指定排除Filter條件的類。
- useDefaultFilters=true/false:指定是否需要使用Spring默認(rèn)的掃描規(guī)則:被@Component, @Repository, @Service, @Controller或者已經(jīng)聲明過(guò)@Component自定義注解標(biāo)記的組件;
在過(guò)濾規(guī)則Filter中:
FilterType:指定過(guò)濾規(guī)則,支持的過(guò)濾規(guī)則有:
- ANNOTATION:按照注解規(guī)則,過(guò)濾被指定注解標(biāo)記的類(默認(rèn));
- ASSIGNABLE_TYPE:按照給定的類型;
- ASPECTJ:按照ASPECTJ表達(dá)式;
- REGEX:按照正則表達(dá)式;
- CUSTOM:自定義規(guī)則,自定義的Filter需要實(shí)現(xiàn)TypeFilter接口;
value和classes:指定在該規(guī)則下過(guò)濾的表達(dá)式;
@ComponentScan的常見(jiàn)的配置如下:
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
3. @ComponentScan過(guò)濾規(guī)則說(shuō)明
規(guī)則表達(dá)式說(shuō)明
1. 掃描指定類文件
@ComponentScan(basePackageClasses = Person.class)
2. 掃描指定包,使用默認(rèn)掃描規(guī)則,即被@Component, @Repository, @Service, @Controller或者已經(jīng)聲明過(guò)@Component自定義注解標(biāo)記的組件;
@ComponentScan(value = "com.example")
3. 掃描指定包,加載被@Component注解標(biāo)記的組件和默認(rèn)規(guī)則的掃描(因?yàn)閡seDefaultFilters默認(rèn)為true)
@ComponentScan(value = "com.example", includeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
4. 掃描指定包,只加載Person類型的組件
@ComponentScan(value = "com.example", includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Person.class) }, useDefaultFilters = false)
5. 掃描指定包,過(guò)濾掉被@Component標(biāo)記的組件
@ComponentScan(value = "com.example", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
6. 掃描指定包,自定義過(guò)濾規(guī)則
@ComponentScan(value = "com.example", includeFilters = { @Filter(type = FilterType.CUSTOM, value = MtyTypeFilter.class) }, useDefaultFilters = true)
4. 自定義掃描過(guò)濾規(guī)則
用戶自定義掃描過(guò)濾規(guī)則,需要實(shí)現(xiàn)org.springframework.core.type.filter.TypeFilter接口。
//1.自定義類實(shí)現(xiàn)TypeFilter接口并重寫match()方法
public class MtyTypeFilter implements TypeFilter {
/**
*
* @param metadataReader:讀取到當(dāng)前正在掃描的類的信息
* @param metadataReaderFactory:可以獲取到其他任何類的信息
* @return
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
System.out.println("========MtyTypeFilter===========");
//獲取當(dāng)前類的注解的信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
System.out.println("annotationMetadata: "+annotationMetadata);
//輸出結(jié)果:annotationMetadata: com.example.test.bean.Color
//獲取當(dāng)前正在掃描的類的類信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
System.out.println("classMetadata: "+classMetadata);
//輸出結(jié)果: classMetadata: com.example.test.bean.Color
//獲取當(dāng)前類資源(類的路徑)
Resource resource = metadataReader.getResource();
System.out.println("resource: "+resource);
//輸出結(jié)果:resource: file [D:\idea\demo-02\target\classes\com\example\test\bean\Color.class]
//獲取類名
String className = classMetadata.getClassName();
System.out.println("className: "+className);
//輸出結(jié)果:className: com.example.test.bean.Color
Class<?> forName = null;
try {
forName = Class.forName(className);
if (Color.class.isAssignableFrom(forName)) {
// 如果是Color的子類,就加載到IOC容器
return true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("========MtyTypeFilter===========");
return false;
}
}
5. @ComponentScans
可以一次聲明多個(gè)@ComponentScan
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class) //指定ComponentScan可以被ComponentScans作為數(shù)組使用
public @interface ComponentScan {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ComponentScans {
ComponentScan[] value();
}
@ComponentScans(value = { @ComponentScan(value = "com.example.test"),
@ComponentScan(value = "com.example.test", includeFilters = {
@Filter(type = FilterType.CUSTOM, value = MtyTypeFilter.class) }) })
public class MainConfig {
@Bean(name = "pers", initMethod = "init", destroyMethod = "destory")
public Person person() {
return new Person();
}
}
6. spring boot處理@ComponentScan源碼分析
spring創(chuàng)建bean對(duì)象的基本流程是先創(chuàng)建對(duì)應(yīng)的BeanDefinition對(duì)象,然后在基于BeanDefinition對(duì)象來(lái)創(chuàng)建Bean對(duì)象,SpringBoot也是如此,只不過(guò)通過(guò)注解創(chuàng)建BeanDefinition對(duì)象的時(shí)機(jī)和解析方式不同而已。SpringBoot是通過(guò)ConfigurationClassPostProcessor這個(gè)BeanFactoryPostProcessor類來(lái)處理。
本演示的demo涉及到4個(gè)演示類,分別是:
- 帶有@SpringBootApplication注解的啟動(dòng)類Demo02Application。
- 帶有@RestController注解的類HelloController。
- 帶有@Configuration注解且有通過(guò)@Bean注解來(lái)創(chuàng)建addInterceptors的方法的MyMvcConfig類。
- Account實(shí)體類無(wú)任何注解。
本文的最后會(huì)貼出所有代碼。 先從啟動(dòng)類為入口,SpringBoot啟動(dòng)類如下:
@SpringBootApplication
public class Demo02Application {
public static void main(String[] args) {
//1、返回我們IOC容器
ConfigurableApplicationContext run = SpringApplication.run(Demo02Application.class, args);
}
}
從SpringApplication.run(Demo02Application.class, args);一路斷點(diǎn)到核心方法SpringApplication.ConfigurableApplicationContext run(String... args)方法
run方法干了兩件事:
- 創(chuàng)建SpringApplication對(duì)象
- 利用創(chuàng)建好的SpringApplication對(duì)象調(diào)用run方法
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
ConfigurableApplicationContext context = null;
this.configureHeadlessProperty();
//初始化監(jiān)聽器
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//發(fā)布ApplicationStartingEven
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
//裝配參數(shù)和環(huán)境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//發(fā)布ApplicationEnvironmentPreparedEvent
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
this.configureIgnoreBeanInfo(environment);
Banner printedBanner = this.printBanner(environment);
//創(chuàng)建ApplicationContext,并裝配
context = this.createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
//發(fā)布ApplicationPreparedEvent
this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup);
}
//發(fā)布ApplicationStartedEven
listeners.started(context, timeTakenToStartup);
//執(zhí)行Spring中@Bean下的一些操作,如靜態(tài)方法
this.callRunners(context, applicationArguments);
} catch (Throwable var12) {
this.handleRunFailure(context, var12, listeners);
throw new IllegalStateException(var12);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
return context;
} catch (Throwable var11) {
this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var11);
}
}
重點(diǎn)方法一:本方法法實(shí)現(xiàn)的重點(diǎn)功能: 本demo是web工程,springboot通過(guò)反射創(chuàng)建上下文context:AnnotationConfigServletWebServerApplicationContext 類在構(gòu)建context的無(wú)參構(gòu)造方法中構(gòu)建成員變量reader=new AnnotatedBeanDefinitionReader(this),在AnnotatedBeanDefinitionReader的無(wú)參構(gòu)造方法中會(huì)beanFactory對(duì)象,并向beanFactory中注冊(cè)5個(gè)BeanDefinition對(duì)象,重點(diǎn)關(guān)注ConfigurationClassPostProcessor。
context = this.createApplicationContext();
重點(diǎn)方法二:本方法實(shí)現(xiàn)的重點(diǎn)功能
本方法會(huì)構(gòu)建啟動(dòng)類Demo02Application對(duì)應(yīng)的BeanDefinition對(duì)象,并注冊(cè)到beanFactory中,此時(shí)的context對(duì)象可見(jiàn)下圖
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
重點(diǎn)方法三:本方法實(shí)現(xiàn)的重點(diǎn)功能
該方法實(shí)際調(diào)用applicationContext的refresh方法,代碼分析詳見(jiàn)我的另一篇博客,本文后面只會(huì)分析ConfigurationClassPostProcessor對(duì)象的創(chuàng)建和postProcessBeanDefinitionRegistry方法的執(zhí)行
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);代碼執(zhí)行后的截圖如下:

ConfigurationClassPostProcessor實(shí)現(xiàn)BeanFactoryPostProcessor,關(guān)于BeanFactoryPostProcessor擴(kuò)展接口的作用在《spring初始化源碼淺析之關(guān)鍵類和擴(kuò)展接口》一文中有詳細(xì)介紹。
ConfigurationClassPostProcessor對(duì)象的創(chuàng)建和方法執(zhí)行的斷點(diǎn)如下:
this.refreshContext(context);–> AbstractApplicationContext.refresh() --> invokeBeanFactoryPostProcessors() -->PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()->invokeBeanDefinitionRegistryPostProcessors()
下面重點(diǎn)看ConfigurationClassPostProcessor類的postProcessBeanDefinitionRegistry()方法如何處理@ComponentScan注解:

同過(guò)源代碼發(fā)現(xiàn)最終是由ConfigurationClassParser的解析類來(lái)處理,繼續(xù)查看ConfigurationClassParser.doProcessConfigurationClass

原來(lái)在這里對(duì)@ComponentScan注解做了判斷,上面一段代碼做了核心的幾件事:
- 掃描@ComponentScan注解包下面的所有的可自動(dòng)裝備類,生成BeanDefinition對(duì)象,并注冊(cè)到beanFactory對(duì)象中。
- 通過(guò)DeferredImportSelectorHandler處理@EnableAutoConfiguration注解,后續(xù)會(huì)有專文介紹。
- 將帶有@Configuration 注解的類解析成ConfigurationClass對(duì)象并緩存,后面創(chuàng)建@Bean注解的Bean對(duì)象所對(duì)應(yīng)的BeanDefinition時(shí)會(huì)用到
到此為止MyFilter2對(duì)應(yīng)的BeanDefinition已創(chuàng)建完畢,如下圖:

總結(jié)
到此這篇關(guān)于spring boot自動(dòng)裝配之@ComponentScan注解用法詳解的文章就介紹到這了,更多相關(guān)@ComponentScan注解用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 基于@ComponentScan注解及其XML配置方式
- 關(guān)于@ComponentScan注解的用法及作用說(shuō)明
- SpringBoot中@ComponentScan注解過(guò)濾排除不加載某個(gè)類的3種方法
- @AutoConfigurationPackage與@ComponentScan注解區(qū)別
- Spring @ComponentScan注解使用案例詳細(xì)講解
- Spring @ComponentScan注解掃描組件原理
- Spring?component-scan?XML配置與@ComponentScan注解配置
- 基于ComponentScan注解的掃描范圍及源碼解析
相關(guān)文章
Java AbstractMethodError原因案例詳解
這篇文章主要介紹了Java AbstractMethodError原因案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
SpringBoot2整合Ehcache組件實(shí)現(xiàn)輕量級(jí)緩存管理
EhCache是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、上手簡(jiǎn)單等特點(diǎn),是Hibernate中默認(rèn)的緩存提供方。本文講述下SpringBoot2 整合Ehcache組件的步驟2021-06-06
Java實(shí)現(xiàn)短信驗(yàn)證碼詳細(xì)過(guò)程
這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)短信驗(yàn)證碼的相關(guān)資料, 在業(yè)務(wù)需求中我們經(jīng)常會(huì)用到短信驗(yàn)證碼,比如手機(jī)號(hào)登錄、綁定手機(jī)號(hào)、忘記密碼、敏感操作等,需要的朋友可以參考下2023-09-09
Java后臺(tái)批量生產(chǎn)echarts圖表并保存圖片
這篇文章主要介紹了Java后臺(tái)批量生產(chǎn)echarts圖表并保存圖片,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
SpringBoot項(xiàng)目打包發(fā)布到外部tomcat(出現(xiàn)各種異常的解決)
這篇文章主要介紹了SpringBoot項(xiàng)目打包發(fā)布到外部tomcat(出現(xiàn)各種異常的解決),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
JAVA實(shí)現(xiàn)二維碼生成加背景圖代碼實(shí)例
這篇文章主要介紹了JAVA實(shí)現(xiàn)二維碼生成加背景圖代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
關(guān)于gradle多模塊項(xiàng)目依賴管理方式
這篇文章主要介紹了關(guān)于gradle多模塊項(xiàng)目依賴管理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04

