spring boot自动装配之@ComponentScan注解用法详解

 更新时间:2023年04月28日 11:03:49   作者:qq_39093474  
@ComponentScan的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中,下面这篇文章主要给大家介绍了关于spring boot自动装配之@ComponentScan注解用法的相关资料,需要的朋友可以参考下

1.@ComponentScan注解作用

@ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里。会被自动装配的注解包括@Controller@Service@Component@Repository等等。与ComponentScan注解相对应的XML配置就是<context:component-scan/>, 根据指定的配置自动扫描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默认的扫描规则:被@Component, @Repository, @Service, @Controller或者已经声明过@Component自定义注解标记的组件;

在过滤规则Filter中:

FilterType:指定过滤规则,支持的过滤规则有:

  • ANNOTATION:按照注解规则,过滤被指定注解标记的类(默认);
  • ASSIGNABLE_TYPE:按照给定的类型;
  • ASPECTJ:按照ASPECTJ表达式;
  • REGEX:按照正则表达式;
  • CUSTOM:自定义规则,自定义的Filter需要实现TypeFilter接口;

value和classes:指定在该规则下过滤的表达式;

@ComponentScan的常见的配置如下:

@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)

3. @ComponentScan过滤规则说明

规则表达式说明

 1. 扫描指定类文件
   @ComponentScan(basePackageClasses = Person.class)
 2. 扫描指定包,使用默认扫描规则,即被@Component, @Repository, @Service, @Controller或者已经声明过@Component自定义注解标记的组件;
   @ComponentScan(value = "com.example")
 3. 扫描指定包,加载被@Component注解标记的组件和默认规则的扫描(因为useDefaultFilters默认为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. 扫描指定包,过滤掉被@Component标记的组件
   @ComponentScan(value = "com.example", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
 6. 扫描指定包,自定义过滤规则
   @ComponentScan(value = "com.example", includeFilters = { @Filter(type = FilterType.CUSTOM, value = MtyTypeFilter.class) }, useDefaultFilters = true)

4. 自定义扫描过滤规则

用户自定义扫描过滤规则,需要实现org.springframework.core.type.filter.TypeFilter接口。

//1.自定义类实现TypeFilter接口并重写match()方法
public class MtyTypeFilter implements TypeFilter {
    /**
     *
     * @param metadataReader:读取到当前正在扫描的类的信息
     * @param metadataReaderFactory:可以获取到其他任何类的信息
     * @return
     * @throws IOException
     */
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        System.out.println("========MtyTypeFilter===========");
        //获取当前类的注解的信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        System.out.println("annotationMetadata: "+annotationMetadata);
        //输出结果:annotationMetadata: com.example.test.bean.Color

        //获取当前正在扫描的类的类信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        System.out.println("classMetadata: "+classMetadata);
        //输出结果: classMetadata: com.example.test.bean.Color

        //获取当前类资源(类的路径)
        Resource resource = metadataReader.getResource();
        System.out.println("resource: "+resource);
        //输出结果:resource: file [D:\idea\demo-02\target\classes\com\example\test\bean\Color.class]


        //获取类名
        String className = classMetadata.getClassName();
        System.out.println("className: "+className);
        //输出结果: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

可以一次声明多个@ComponentScan

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)  //指定ComponentScan可以被ComponentScans作为数组使用
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创建bean对象的基本流程是先创建对应的BeanDefinition对象,然后在基于BeanDefinition对象来创建Bean对象,SpringBoot也是如此,只不过通过注解创建BeanDefinition对象的时机和解析方式不同而已。SpringBoot是通过ConfigurationClassPostProcessor这个BeanFactoryPostProcessor类来处理。

本演示的demo涉及到4个演示类,分别是:

  1. 带有@SpringBootApplication注解的启动类Demo02Application。
  2. 带有@RestController注解的类HelloController。
  3. 带有@Configuration注解且有通过@Bean注解来创建addInterceptors的方法的MyMvcConfig类。
  4. Account实体类无任何注解。

本文的最后会贴出所有代码。 先从启动类为入口,SpringBoot启动类如下:

@SpringBootApplication
public class Demo02Application {

    public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(Demo02Application.class, args);
	}
}

SpringApplication.run(Demo02Application.class, args);一路断点到核心方法SpringApplication.ConfigurableApplicationContext run(String... args)方法

run方法干了两件事:

  • 创建SpringApplication对象
  • 利用创建好的SpringApplication对象调用run方法
 public ConfigurableApplicationContext run(String... args) {
        long startTime = System.nanoTime();
        DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
        ConfigurableApplicationContext context = null;
        this.configureHeadlessProperty();
        //初始化监听器
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //发布ApplicationStartingEven
        listeners.starting(bootstrapContext, this.mainApplicationClass);

        try {
        	 //装配参数和环境
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //发布ApplicationEnvironmentPreparedEvent
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            Banner printedBanner = this.printBanner(environment);
            //创建ApplicationContext,并装配
            context = this.createApplicationContext();
            context.setApplicationStartup(this.applicationStartup);
            //发布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);
            }
			//发布ApplicationStartedEven
            listeners.started(context, timeTakenToStartup);
            //执行Spring中@Bean下的一些操作,如静态方法
            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);
        }
    }

重点方法一:本方法法实现的重点功能: 本demoweb工程,springboot通过反射创建上下文context:AnnotationConfigServletWebServerApplicationContext 类在构建context的无参构造方法中构建成员变量reader=new AnnotatedBeanDefinitionReader(this),在AnnotatedBeanDefinitionReader的无参构造方法中会beanFactory对象,并向beanFactory中注册5个BeanDefinition对象,重点关注ConfigurationClassPostProcessor。

context = this.createApplicationContext();

重点方法二:本方法实现的重点功能

本方法会构建启动类Demo02Application对应的BeanDefinition对象,并注册到beanFactory中,此时的context对象可见下图

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

重点方法三:本方法实现的重点功能

该方法实际调用applicationContext的refresh方法,代码分析详见我的另一篇博客,本文后面只会分析ConfigurationClassPostProcessor对象的创建和postProcessBeanDefinitionRegistry方法的执行

    this.refreshContext(context);
    this.afterRefresh(context, applicationArguments);

this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);代码执行后的截图如下:

ConfigurationClassPostProcessor实现BeanFactoryPostProcessor,关于BeanFactoryPostProcessor扩展接口的作用在《spring初始化源码浅析之关键类和扩展接口》一文中有详细介绍。

ConfigurationClassPostProcessor对象的创建和方法执行的断点如下:
this.refreshContext(context);–> AbstractApplicationContext.refresh() --> invokeBeanFactoryPostProcessors() -->PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()->invokeBeanDefinitionRegistryPostProcessors()

下面重点看ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry()方法如何处理@ComponentScan注解:

同过源代码发现最终是由ConfigurationClassParser的解析类来处理,继续查看ConfigurationClassParser.doProcessConfigurationClass

原来在这里对@ComponentScan注解做了判断,上面一段代码做了核心的几件事:

  1. 扫描@ComponentScan注解包下面的所有的可自动装备类,生成BeanDefinition对象,并注册到beanFactory对象中。
  2. 通过DeferredImportSelectorHandler处理@EnableAutoConfiguration注解,后续会有专文介绍。
  3. 将带有@Configuration 注解的类解析成ConfigurationClass对象并缓存,后面创建@Bean注解的Bean对象所对应的BeanDefinition时会用到

到此为止MyFilter2对应的BeanDefinition已创建完毕,如下图:

总结 

到此这篇关于spring boot自动装配之@ComponentScan注解用法详解的文章就介绍到这了,更多相关@ComponentScan注解用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现动物换位游戏完整 过程详解

    Java实现动物换位游戏完整 过程详解

    大家好,今天尝试用Java编程设计一个GUI界面的动物换位游戏,游戏的结果是让左右两组的动物交换位置,以下是具体设计过程,供大家参考
    2022-07-07
  • java Executors常用线程池

    java Executors常用线程池

    这篇文章主要为大家介绍了java Executors中提供的几种常用的线程池使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • 解决IDEA创建第一个spring boot项目提示cannot resolve xxx等错误

    解决IDEA创建第一个spring boot项目提示cannot resolve xxx等

    这篇文章主要介绍了解决IDEA创建第一个spring boot项目提示cannot resolve xxx等错误问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Springboot项目实现将类从@ComponentScan中排除

    Springboot项目实现将类从@ComponentScan中排除

    这篇文章主要介绍了Springboot项目实现将类从@ComponentScan中排除,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • IDEA中的Structure模块使用图文详解

    IDEA中的Structure模块使用图文详解

    IDEA 的 Structure 功能,也是在看代码中一个十分常用的功能,最通用的方法,就是点击 IDEA 左下角的 Structure 标签页即可,本文重点介绍IDEA中的Structure模块使用详解,感兴趣的朋友跟随小编一起看看吧
    2024-03-03
  • Java中接口的深入详解

    Java中接口的深入详解

    在Java语言中,接口由类来实现以便使用接口中的方法,这篇文章主要给大家介绍了关于Java中接口的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-11-11
  • Java 括号匹配问题案例详解

    Java 括号匹配问题案例详解

    这篇文章主要介绍了Java 括号匹配问题案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Java并发 结合源码分析AQS原理

    Java并发 结合源码分析AQS原理

    这篇文章主要介绍了Java并发 结合源码分析AQS原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • IDEA里找不到Maven的有效解决办法(小白超详细)

    IDEA里找不到Maven的有效解决办法(小白超详细)

    这篇文章主要给大家介绍了关于IDEA里找不到Maven的有效解决办法,文中通过图文将解决的办法介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • Java运行环境搭建的图文教程

    Java运行环境搭建的图文教程

    下面小编就为大家带来一篇Java运行环境搭建的图文教程。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09

最新评论