• SpringBoot的自动配置


    前言

    在使用SpringBoot时,如果我们直接引入第三方包,那么这些第三包中的Bean对象是不会被直接加入到IOC容器中,如果想要将第三方包中的Bean对象加入到IOC容器中,我们只能手写配置类@Configuration或是使用@Import引入Bean对象所在的类。但是在实际开发中,一些第三方开发者提供了形如xxx-spring-boot-starter的依赖包,引入这些依赖包后,我们会惊讶的发现,这些第三方包中的Bean对象居然直接的自动注入到IOC容器中,其实这就运用了SpringBoot的自动配置原理

    自动配置原理的两个包

    • xxx-spring-boot-starter
      自动配置原理的启动类,一个只有pom.xml文件没有任何源代码的maven工程,作为入口导入配置类和其他项目中的被依赖包
      在这里插入图片描述

    • xxx-spring-boot-autoconfigure
      自动配置原理的实现类,用于封装Java代码,和配置需要用到的依赖,同时需要编写resources/META-INF/spring.factories文件或META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定SpringBoot启动时装载的配置类
      在这里插入图片描述

    xxx-springboot-starter中pom.xml的实现

    引入xxx-spring-boot-autoconfigure就好了,其他都不需要弄

            <dependency>
                <groupId>com.examplegroupId>
                <artifactId>tencent-spring-boot-autoconfigureartifactId>
                <version>0.0.1-SNAPSHOTversion>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    xxx-springboot-autoconfigure的实现

    在src下编写实现类和业务代码,之后创建一个配置类作为SpringBoot导入Bean对象的入口

    //配置类代码如下
    @Configuration
    //这个是构造Bean时需要引入的参数
    @EnableConfigurationProperties(TencentProperties.class)
    public class TencentAutoConfiguration {
        @Bean
        public TencentCloud tencentCloud(TencentProperties tencentProperties){
            TencentCloud tencentCloud=new TencentCloud();
            tencentCloud.setTencentProperties(tencentProperties);
            return tencentCloud;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    此外还需要在resources/META-INF/spring.factories文件或META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中声明配置类的信息

    • spring.factories
    # Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\     #这个是固定格式
    com.example.tencentspringbootautoconfigure.TencentAutoConfiguration  #这个是你自己的Configuration类的包路径
    
    • 1
    • 2
    • 3
    • org.springframework.boot.autoconfigure.AutoConfiguration.imports
    # Auto Configure
    com.example.tencentspringbootautoconfigure.TencentAutoConfiguration  #这个是你自己的Configuration类的包路径
    
    • 1
    • 2

    上面二选一即可

    打包

    maven install配置类,再maven install启动类即可生成你自己的starter依赖包,接下来可以直接在项目中引用了。此时第三方依赖包中的Bean对象就自动注入到IOC容器中了,你可以直接通过@Autowired使用了

  • 相关阅读:
    深度学习——(2)几种常见的损失函数
    linux终端切换python版本
    网络编程、socket编程、多进程并发服务器
    半导体新能源智能装备上位机工业软件设计方案
    香港科技大学广州|先进材料学域博士招生宣讲会—上海专场!!!(暨全额奖学金政策)
    LabVIEW将 VI 升级到较新的版本和恢复为先前版本
    Osgb转3DTiles工具
    修复微信小程序不能获取头像和昵称的bug,微信小程序新版头像昵称API使用
    基于Java毕业设计医友医院信息管理源码+系统+mysql+lw文档+部署软件
    (17)Blender源码分析之闪屏窗口的菜单显示过程
  • 原文地址:https://blog.csdn.net/qq_33880925/article/details/134024831