SpringBoot自动配置原理,你真的懂吗?

SpringBoot自动配置原理,你真的懂吗?上面博文我们简单的介绍了什么是 SpringBoot 以及如何使用 SpringBoot 但是我们对于 SpringBoot 的基本原理并没有介绍 这篇博文我们重点介绍 SpringBoot 是如何实现的自动配置 依赖管理在我们的 pom 文件中最核心的依赖就一个 parent groupId org springframew boot groupId artifactId spring boot starter parent lt artifactId parent

概述

上面博文(SpringBoot简介与快速搭建)我们简单的介绍了什么是SpringBoot,以及如何使用SpringBoot,但是我们对于SpringBoot的基本原理并没有介绍,这篇博文我们重点介绍SpringBoot是如何实现的自动配置。


依赖管理

在我们的pom文件中最核心的依赖就一个:

<parent> <groupId>org.springframework.boot 
      groupId> <artifactId>spring-boot-starter-parent 
       artifactId> <version>2.4.4 
        version> <relativePath/>  
         parent> 

它的父项目依赖,规定所有依赖的版本信息:

<parent> <groupId>org.springframework.boot 
      groupId> <artifactId>spring-boot-dependencies 
       artifactId> <version>2.4.4 
        version>  
         parent> 

由此,我们发现springboot框架几乎声明了所有开发中常用的依赖的版本号,无需关注版本号,而且实现了自动版本仲裁机制,当然了我们也可以根据我们的需要,替换掉默认的依赖版本。


核心注解@SpringBootApplication

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

在上面的启动类中我们发现了一个陌生的注解@SpringBootApplication,这个注解的是什么含义呢?我们点进去看一下。

@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { 
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) 

其实@SpringBootApplication是上面三个注解的组合体,我们对这三个注解理解清楚就可以了,下面逐个进行解释:


@SpringBootConfiguration

@Configuration public @interface SpringBootConfiguration { 
       

@Configuration我们并不陌生,它允许在上下文中注册额外的bean或导入其他配置类,@SpringBootConfiguration其实代表当前类是一个配置类。


@EnableAutoConfiguration

EnableAutoConfiguration的目的是启动SpringBoot的自动配置机制。

@AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { 
        

1、AutoConfigurationPackage指定默认的包规则

@Import(AutoConfigurationPackages.Registrar.class) public @interface AutoConfigurationPackage { 
        

AutoConfigurationPackage注解的作用是将 添加该注解的类所在的package 作为 自动配置package 进行管理。也就是说当SpringBoot应用启动时默认会将启动类所在的package作为自动配置的package。然后使用@Import注解将其注入到ioc容器中。这样,可以在容器中拿到该路径。

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { 
        @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { 
        register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0])); } @Override public Set<Object> determineImports(AnnotationMetadata metadata) { 
        return Collections.singleton(new PackageImports(metadata)); } } 

重点看下registerBeanDefinitions方法。

方法的第二个参数通过new PackageImport(metadata).getPackageName()方法设置。

接着看下PackageImport的构造器方法。

PackageImports(AnnotationMetadata metadata) { 
        AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); List<String> packageNames = new ArrayList<>(Arrays.asList(attributes.getStringArray("basePackages"))); for (Class<?> basePackageClass : attributes.getClassArray("basePackageClasses")) { 
        packageNames.add(basePackageClass.getPackage().getName()); } if (packageNames.isEmpty()) { 
        packageNames.add(ClassUtils.getPackageName(metadata.getClassName())); } this.packageNames = Collections.unmodifiableList(packageNames); } 

ClassUtils.getPackageName(metadata.getClassName())获取标注@AutoConfigurationPackage注解的类的全限定名。

最后,利用Registrar给容器中导入一系列组件,将指定的包下的所有组件导入进来。

2、@Import(AutoConfigurationImportSelector.class)

使用Import自动导入所有符合自动配置条件的Bean定义并加载到IOC容器

@Override public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) { 
        Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) .getAutoConfigurationEntry(annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { 
        this.entries.putIfAbsent(importClassName, annotationMetadata); } } 

在这里插入图片描述

文件里面写死了spring-boot一启动就要给容器中加载的所有配置类spring-boot-autoconfigure-2.4.4.RELEASE.jar/META-INF/spring.factories,一共130个自动配置类。

130个场景的所有自动配置,会在springboot启动的时候默认全部加载。xxxxAutoConfiguration会按照条件装配规则(@Conditional),最终会按需配置。

小结:

SpringBoot为我们的应用程序启用了三个功能:自动配置,组件扫描,以及能够在”应用类”上定义额外的配置。


@ComponentScan

@Component在应用程序所在的软件包上启用扫描,指定扫描哪些Spring注解。


ServletWebServerFactoryAutoConfiguration为例

在130个场景有我们比较熟悉两个组件,ServletWebServerFactoryAutoConfiguration和WebMvcAutoConfiguration,我们以ServletWebServerFactoryAutoConfiguration为例,看一下SpringBoot是如何自动装配的webServer。

在这里插入图片描述

在注解中我们看到了大量以@Conditional开头的注解,即条件装配,满足Conditional指定的条件,则进行组件注入。@EnableConfigurationProperties(ServerProperties.class)+@ConfigurationProperties(prefix = “server”, ignoreUnknownFields = true),读取我们在配置文件编写的属性,并把它封装到JavaBean中,以供随时使用。

此时我们的Tomcat容器已经以Bean的形式被注入到了IOC容器中。


如何禁用特定的自动配置类

如果发现应用中不需要特定自动配置类,则可以使用exclude属性@SpringBootApplication来禁用它们,如以下示例所示:

import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; @SpringBootApplication(exclude={ 
          DataSourceAutoConfiguration.class}) //@SpringBootApplication(excludeName = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"}) public class MyApplication { 
           } 

如果该类不在类路径中,则可以使用excludeName注释的属性,并指定完全限定的名称(全类名字符串)。定义排除项,即可以使用哪个注释级别也可以使用属性来定义。


总结

  • SpringBoot预先加载META-INF/spring.factories中所有的自动配置类,xxxxxAutoConfiguration
  • 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
  • 生效的配置类就会给容器中装配很多组件,只要容器中有这些组件,相当于有了这些功能
  • 定制化配置
    • 用户直接自己@Bean替换底层的组件
    • 用户根据这个组件是获取的配置文件的什么值,可以自行修改。

EnableAutoConfiguration —> 扫描xxxxxAutoConfiguration —> 根据条件@Conditional装配组件 —>根据xxxxProperties加载属性值 —-> application.properties


博主写作不易,加个关注呗

求关注、求点赞,加个关注不迷路,感谢

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220710.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午7:50
下一篇 2026年3月17日 下午7:50


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号