springBoot 如何实现自动装板

前言

  如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。
  而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那欢迎常来啊!!!


springBoot 如何实现自动装板

01 前期了解

01::01 什么是Spring 的 IOC容器(控制反转)

spring的IOC容器:
指的是控制反转,IOC容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。交由Spring容器统一进行管理,从而实现松耦合。
即由Ioc容器来控制对 象的创建。

01::02 IOC容器实现过程

  1. 包扫描
  2. 把带有@Configuration/@Component的class对象加载到内存中

@Configuration ----------->>> 等同于bean.xml

  1. 生成各种class的bean定义,整合到BeanDefinitionMap<beanName,BeanDefinition>中

beanName—bean的名称
beanDefinition对象—描述bean实例化的各个属性

  1. 从BeanDefinitionMap<beanName,BeanDefinition>取出bean定义,一个一个进行实例化。

扩展:

spring提供一个扩展机会,在bean还没实例化之前修改我们bean定义的属性{
BeanFactoryPostProcessor 接口 --> 扩展bean 的自定义属性 控制实例bean的行为
}


02 springBoot 如何实现自动装板

02::01 概述

就是通过@Import(value="")去读取spring.factories配置文件,把里面的配置类解析成一个一个的bean定义,并导入BeanDefinitionMap<beanName,BeanDefinition>中。

02::02 装配了什么?

即自动装配类的bde(BeanDefinition)装配到BeanDefinitionMap<beanName,BeanDefinition>中

02::03 源码层面解读

找到主启动类点击@SpringBootApplication,可以看到

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {
    
    @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    AutoConfigurationExcludeFilter.class}
)}
)

对于springBoot 的自动装配由三个方面的支持来实现:
包扫描:
@SpringBootApplication -> @ComponentScan 路径扫描(根据这个主启动类所在包开始扫描)。

举例 :@RestController只能写在主启动类所在包的子包下,否则会扫描不到。

查询配置类:
@SpringBootApplication -> @SpringBootConfiguration -> @Configuration (配置类)

自动装配:
有个重点的注解@Import,这个是springBoot自动装配的关键所在。
@SpringBootApplication
-> @EnableAutoConfiguration
->@Import({AutoConfigurationImportSelector.class})

点进AutoConfigurationImportSelector有个关键的方法,即获取要自动装配的基础,就是要装配的全类名。
下面是关键方法的部分源码:

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
    
    

    public String[] selectImports(AnnotationMetadata annotationMetadata) {
    
    
    ...
        if (!this.isEnabled(annotationMetadata)) {
    
    
            return NO_IMPORTS;
        } else {
    
    
            AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
        ...
    }
}

这个方法的大概作用:
查找META-INF/spring.factories(所有的整合都在这个自动装配类中的spring.factories文件里)
去重,排除
最后组成我们所需要的bean的全类名
即返回值就是导入容器中的bean定义

META-INF/spring.factories文件:
在这里插入图片描述
内容:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38316697/article/details/119826785
今日推荐