Spring Boot自动配置原理 - Java技术债务


@SpringBootApplication

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_1.jpg

@SpringBootApplication注解由@SpringBootConfiguration、@ComponentScan、@EnableAutoConfiguration三个注解组成

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_2.jpg

  • @SpringBootConfiguration:我们点进去以后可以发现底层是Configuration注解,说白了就是支持JavaConfig的方式来进行配置(使用Configuration配置类等同于XML文件)。
  • @EnableAutoConfiguration:开启自动配置功能
  • @ComponentScan扫描注解,默认是扫描当前类下的package。将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中。

所以SpringBoot入口类可以写成:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class KnowledgeBaseApplication {

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

@EnableAutoConfiguration

我们知道SpringBoot可以帮我们减少很多的配置,也肯定听过“约定大于配置”这么一句话,那SpringBoot是怎么做的呢?其实靠的就是@EnableAutoConfiguration注解。

简单来说,这个注解可以帮助我们自动载入应用程序所需要的所有默认配置

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_3.jpg

  • @AutoConfigurationPackage:自动配置包
  • @Import:给IOC容器导入组件

@AutoConfigurationPackage

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_4.jpg

图中所示依靠@Import注解。点进去看重要的代码是:

@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
        BeanDefinitionRegistry registry) {
    register(registry, new PackageImport(metadata).getPackageName());
}

默认的情况下就是将:主配置类(@SpringBootApplication)的所在包及其子包里边的组件扫描到Spring容器中。

注意:

  • @Controller/@Service/@Component/@Repository这些注解是由ComponentScan来扫描并加载的。
  • 诸如 @Entity 此类的注解是由@AutoConfigurationPackage扫描并加载

@Import

AutoConfigurationImportSelector.class

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_5.jpg

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_6.jpg

此时只看到了SpringFactoriesLoader.loadFactoryNames()方法加载

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_7.jpg

此时可以知道:

  • FACTORIES_RESOURCE_LOCATION的值是META-INF/spring.factories
  • Spring启动的时候会扫描所有jar路径下的META-INF/spring.factories,将其文件包装成Properties对象
  • 从Properties对象获取到key值为EnableAutoConfiguration的数据,然后添加到容器里边。

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_8.jpg

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_9.jpg

总结

@SpringBootApplication等同于下面三个注解:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

其中@EnableAutoConfiguration是关键(启用自动配置)该注解又通过 @Import 注解导入了AutoConfigurationImportSelector类,在该类中加载 META-INF/spring.factories 的配置信息。然后筛选出以 EnableAutoConfiguration 为 key 的数据,加载到 IOC 容器中,实现自动配置功能!

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_10.jpg

https://www.cuizb.top/myblog/static/image/SpringBoot_autoConfig_11.jpg

   登录后才可以发表呦...

专注分享Java技术干货,包括
但不仅限于多线程、JVM、Spring Boot
Spring Cloud、 Redis、微服务、
消息队列、Git、面试题 最新动态等。

想交个朋友吗
那就快扫下面吧


微信

Java技术债务

你还可以关注我的公众号

会分享一些干货或者好文章

Java技术债务