Spring Boot 自动装配原理

时间:2022-07-22
本文章向大家介绍Spring Boot 自动装配原理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原理初探

springboot 为我们封装了大量的xml配置,使得我们构建web程序可以实现开箱即用

0x01 自动配置

pom.xml

  • spring-boot-dependencies: 核心的依赖在父工程中
  • 我们在写或者引入一些springboot的依赖时,不需要指定版本号,因为在父级依赖中已经帮我们指定好了

0x02 启动器

springboot将所有的功能都变成了一个个的启动器

pom.xml

    <dependencies>
        <!--web环境启动器-->
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

比如在上面的配置中的spring-boot-starter-web 为我们导入了web环境所需的所有依赖

我们需要上面功能,只要找到对应的启动器starter就行了,在以下链接中可以看到springboot官网提供的一些启动器

0x03 主程序

//@SpringBootApplication: 该注解标注这是一个springboot应用:启动类下的所有资源被导入
@SpringBootApplication
public class FirstSpringbootApplication {
    public static void main(String[] args) {
        //将springboot应用启动
        SpringApplication.run(FirstSpringbootApplication.class, args);
    }
}

涉及到的原理太多,后续再补充

个人觉得入门阶段不应该卡在原理这里花太多时间,应该尽快进入实战阶段,但是相关的springboot配置原理不能落下,该做笔记的还是要做,有过相关的实战经验过后再回来探究原理的价值更高。