SpringBoot——自动装配原理

自动配置

pom.xml

  • SpringBoot-dependencies:核心依赖在父工程中
  • 在引入一些SpringBoot依赖的时候,不需要指定版本,因为有版本的仓库
    在这里插入图片描述

启动器

  • SpringBoot的启动场景,比如下面就使用了spring-boot-starter-web,就会帮我们自动导入web环境所有的依赖
  • SpringBoot会将所有的功能场景,都变成一个一个的启动器
  • 我们要使用什么功能,就只需要找到对应的启动器就可以

在这里插入图片描述

 <dependencies>
        <dependency>
            <!--启动器-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

在这里插入图片描述

主程序

//标注这个类是一个Springboot的应用
@SpringBootApplication
public class SpringBootStudyApplication {
        //将SpringBoot应用启动,利用反射
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStudyApplication.class, args);
    }
}

注解

在这里插入图片描述

@SpringBootConfiguration  spring boot的配置  由外到内
    @Configuration spring配置类
         @Component 说明这也是一个spring的组件

@EnableAutoConfiguration   自动配置
     @AutoConfigurationPackage 自动配置包
         @Import({Registrar.class})  导入选择器 元数据包注册
     @Import({AutoConfigurationImportSelector.class})自动导入选择
           List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);

获得候选的配置

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;
    }

META-INF/spring.factories :自动配置的核心文件
在这里插入图片描述
在这里插入图片描述

流程

在这里插入图片描述

结论

springboot所有自动配置都是在启动的时候扫描并加载: spring.factories 所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器了,有了启动器,我们自动装配就会生效,然后就配置成功!

流程

1. SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值
2. 将这些值作为自动配置类导入容器 , 自动配置类就生效 , 帮我们进行自动配置工作;
3. 整个J2EE的整体解决方案和自动配置都在springboot-autoconfigure的jar包中;
4. 它会给容器中导入非常多的自动配置类 (xxxAutoConfiguration), 就是给容器中导入这个场景需要的所有组件 , 并自动配置好这些组件,利用@Configuration ;
5. 有了自动配置类 , 免去了我们手动编写配置注入功能组件等的工作

启动

在这里插入图片描述
SpringApplication.run
该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;

SpringApplication
这个类主要做了以下四件事情:
1、推断应用的类型是普通的项目还是Web项目
2、查找并加载所有可用初始化器 , 设置到initializers属性中
3、找出所有的应用程序监听器,设置到listeners属性中
4、推断并设置main方法的定义类,找到运行的主类
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值