Springboot自动装配源码分析

版本

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

我们进入SpringBootApplication注解看看有什么 

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

我们可以发现有一个@EnableAutoConfiguration注解,这个是实现自动装配的,继续进去看看

@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}
)}
)
public @interface SpringBootApplication {
***
}

我们又看到了一个@Import({AutoConfigurationImportSelector.class})

他代表引入了AutoConfigurationImportSelector.class这个类,核心类,我们看看他的内容

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

可以看到他继承了DeferredImportSelector类,这个类继承了ImportSelector 类。

然后前面说这个类是@Import引入的

@Import有三种使用的方法,其中一种,如果引入的类实现了ImportSelector接口,那么不会把引入的类加入容器,而是实现ImportSelector接口下的一个方法selectImports。

  • 导入普通类
  • 导入实现了ImportSelector接口的类
  • 导入实现了ImportBeanDefinitionRegistrar接口的类
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
****
}
public interface DeferredImportSelector extends ImportSelector {
***
}

这一句就是获取自动装配类的核心代码,我们进入到getAutoConfigurationEntry这个方法中去看,它是怎么获取配置的。

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

这个方法中this.getCandidateConfigurations(annotationMetadata, attributes)就是获取候选的配置类,接下来,我们就进入到getCandidateConfigurations这个方法中去查看SpringBoot是怎么获取这些候选的配置类。

    protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        } else {
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.getConfigurationClassFilter().filter(configurations);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
        }
    }
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

又是这个熟悉的方法SpringFactoriesLoader.loadFactoryNames()

这个方法在springboot启动流程中用到很多次,他就是去meta-inf下加载spring.factories文件。

利用SPI机制去加载配置类

SPI流程:

  1. 有关组织和公式定义接口标准
  2. 第三方提供具体实现: 实现具体方法, 配置 META-INF/services/${interface_name} 文件
  3. 开发者使用

SPI与API区别:

  • API是调用并用于实现目标的类、接口、方法等的描述;
  • SPI是扩展和实现以实现目标的类、接口、方法等的描述;

 

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");

跟我们上面说的一致。

    public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
        String factoryTypeName = factoryType.getName();
        return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
    }
    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            try {
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                LinkedMultiValueMap result = new LinkedMultiValueMap();

                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        String factoryTypeName = ((String)entry.getKey()).trim();
                        String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        int var10 = var9.length;

                        for(int var11 = 0; var11 < var10; ++var11) {
                            String factoryImplementationName = var9[var11];
                            result.add(factoryTypeName, factoryImplementationName.trim());
                        }
                    }
                }

                cache.put(classLoader, result);
                return result;
            } catch (IOException var13) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
            }
        }
    }

参考

深入理解 Java 中 SPI 机制 - 知乎

SpringBoot自动装配原理源码分析(详细)_springboot自动装配源码解析-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/620450.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

GPT搜索鸽了!改升级GPT-4

最近OpenAI太反常&#xff0c;消息一会一变&#xff0c;直让人摸不着头脑。 奥特曼最新宣布&#xff1a;5月13日开发布会&#xff0c;不是GPT-5&#xff0c;也不是盛传的GPT搜索引擎&#xff0c;改成对ChatGP和GPT-4的升级&#xff5e; 消息一出&#xff0c;大伙儿都蒙了。 之…

【cocos creator】2.4.0 import android.support.v4.app.ActivityCompat;失败的解决方案

时间是2024年5月&#xff0c;某cocos creator项目用的是2.4.0编辑器。需求是获取录音权限&#xff0c;需要import ActivityCompat。但是失败&#xff0c;提示Cannot resolve symbol app。 尝试了一些方案失败之后&#xff0c;决定升级cocos creator编辑器版本。升级到2.4.10。…

Maven:继承和聚合

Maven高级 分模块设计和开发 如果在我们自己的项目中全部功能在同一个项目中开发,在其他项目中想要使用我们封装的组件和工具类并不方便 不方便项目的维护和管理 项目中的通用组件难以复用 所以我们需要使用分模块设计 分模块设计 在项目设计阶段,可以将大的项目拆分成若…

【快捷上手】UnrealEngine 的 关卡流 LevelStreaming 的三种加载方式

关键词&#xff1a; Unreal Engine&#xff0c;UE&#xff0c; LevelStreaming&#xff0c;动态&#xff0c;关卡&#xff0c;加载&#xff0c;切换关卡&#xff0c;换地图&#xff0c;子地图&#xff0c;子场景&#xff0c;子关卡&#xff0c;分包加载&#xff0c;动态载入 …

IT服务台的演变趋势

在技术进步和用户期望变化的推动下&#xff0c;IT服务台正在经历重大变化。IT服务台的未来将主要受到以下趋势的推动&#xff1a; 先进的人工智能和认知技术 预计高级人工智能 &#xff08;AI&#xff09; 和认知技术在 IT 服务台中的集成度会更高。通过将 IT 服务台集成到 IT…

点是否在三角形内C++源码实现

原理 思路&#xff1a; 面积和&#xff1a; abc obcaocabo,应该有更简洁的方法&#xff0c;但是这个方法思路更简单 代码实现: 注意二维向量的叉乘后&#xff0c;是垂直于平面的向量&#xff0c;相当于z为0三维向量叉乘&#xff0c;所以只有z维度有值&#xff0c;xy0. flo…

BMS-HiL系统方案设计

系统集成了业内著名 NI 公司的软硬件平台。 系统设计采用分布式设计模式。主控上位机作为整个实验的管理者主要设计软件交互和 流程管理的业务&#xff1b;下位机主要业务为序列执行与设备调用&#xff0c;各模块详细测试方案如下所示。 系统搭建使用 PXI 系统技术&#xff0c;…

98%!汽车贷款行业合成身份欺诈案激增

近年来&#xff0c;合成身份欺诈者以汽车贷款行业为最大目标&#xff0c;导致 2023 年汽车贷款行业的欺诈尝试增加了 98%&#xff0c;损失高达 79 亿美元。Point Predictive 对 1.8 亿份贷款申请的研究发现&#xff0c;收入和就业信息不实、合成身份和信用洗白几乎占汽车贷款机…

vs2017编译libjpeg的32和64位的库

1.下载libjpeg源码&#xff1a;http://www.ijg.org/files/ 2. 我下载的版本是&#xff1a;jpegsr9c.zip 3. 解压jpegsr9c.zip &#xff0c;解压目录&#xff1a;D:\libjpeg\jpeg-9c 4. 将C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include目录下的Win32.Mak文件拷贝…

netty配置SSL、netty配置https(生产环境)

netty配置SSL、netty配置https&#xff08;生产环境&#xff09; 上一篇提到了如何在开发环境使用SSL&#xff1a;https://lingkang.top/archives/netty-pei-zhi-ssl 转自&#xff1a;https://lingkang.top/archives/netty-pei-zhi-https 那么netty如何使用可信任的证书呢&a…

排除对象属性序列化的三种方式

说明&#xff1a;在项目里&#xff0c;经常可以看到以下日志内容&#xff0c;将对象序列化后直接打印出来&#xff0c;观察对象数据&#xff0c;判断当前处理逻辑正确与否。 &#xff08;以下信息来自&#xff1a;https://www.tl.beer/randbankcard.html生成器&#xff0c;信息…

优秀的 Java 项目,代码都是如何分层的?

在Java中&#xff0c;常见的分层结构通常是基于MVC&#xff08;Model-View-Controller&#xff09;或者MVP&#xff08;Model-View-Presenter&#xff09;等设计模式。 1. 模型&#xff08;Model&#xff09;层 模型层主要负责处理数据的逻辑和操作&#xff0c;通常包括以下内…

大学c语言基础很差,能不能学51单片机?会不会很困难?

开始前我分享下我的经历&#xff0c;我刚入行时遇到一个好公司和师父&#xff0c;给了我机会&#xff0c;一年时间从3k薪资涨到18k的&#xff0c; 我师父给了一些51单片机学习方法和资料&#xff0c;让我不断提升自己&#xff0c;感谢帮助过我的人&#xff0c; 如大家和我一样…

小米/红米手机刷机错误:Missmatching image and device

报错&#xff1a; Missmatching image and device。 场景&#xff1a; 该解决方法只适用于手机是通过EMT解锁的。 解决方法&#xff1a; 打开刷机脚本&#xff0c;并注释检测脚本&#xff1a; 刷机脚本根据不同的刷机方式&#xff0c;选择编辑不同的脚本&#xff0c;例如&am…

地图在数字孪生中的7个价值,领导也得点头认可。

地图在数字孪生大屏中扮演着重要的角色&#xff0c;具有以下几个作用&#xff1a; 空间可视化 地图可以将数据在空间上进行可视化展示&#xff0c;将各种信息和指标与地理位置相结合。通过地图的展示&#xff0c;用户可以直观地了解数据在不同地区的分布情况&#xff0c;帮助…

Stable Diffusion拓展Deforum AI视频生成

X轴平移值Z轴位移3D翻转 透视翻转

使用System.Drawing进行几何图形绘制

1.概要 使用System.Drawing进行几何图形绘制 System.Drawing 是.NET框架中的一个命名空间&#xff0c;提供了基本的绘图功能&#xff0c;包括绘制几何图形&#xff08;如矩形、椭圆、线条等&#xff09;。它通常用于Windows Forms应用程序中的绘图。你可以使用 Graphics 类来…

企业级WEB服务Nginx安装

企业级WEB服务Nginx安装 1. Nginx版本和安装方式 Mainline version 主要开发版本,一般为奇数版本号,比如1.19Stable version 当前最新稳定版,一般为偶数版本,如:1.20Legacy versions 旧的稳定版,一般为偶数版本,如:1.18Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安…

我是如何免费抵御一个多月的 DDos/CC 攻击的?

今天明月给大家详细分享一下我的博客是如何免费抵御了长达一个多月的 DDos/CC 攻击的&#xff0c;在【现在 DDos/CC 攻击门槛低的可怕&#xff01;】一文里明月就说过现在 DDos/CC 攻击几乎是没有门槛的&#xff0c;任何一个老鼠屎在群里看到你的博客都可以轻松便捷的发动一次 …

智能优化算法 | Matlab实现KOA开普勒优化算法(内含完整源码)

智能优化算法 | Matlab实现KOA开普勒优化算法(内含完整源码) 文章目录 智能优化算法 | Matlab实现KOA开普勒优化算法(内含完整源码)文章概述源码设计文章概述 智能优化算法 | Matlab实现KOA开普勒优化算法(内含完整源码) 源码设计 %% clear all clc N=25; % Number of s…