SpringBoot 自动装配原理深度解析

玄武2026-03-05字数:494阅读:约 2 分钟springSpring Boot自动装配源码

SpringBoot 自动装配原理深度解析

1. 自动装配是什么?

SpringBoot 自动装配(Auto-Configuration)让开发者无需手动配置大量 Bean,只需引入 starter 依赖,框架自动完成 Bean 的注册和配置。

@SpringBootApplication  // 这一个注解背后做了什么?
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

2. @SpringBootApplication 三合一注解

@SpringBootConfiguration  // 等同于 @Configuration,标识配置类
@EnableAutoConfiguration  // 【核心】开启自动装配
@ComponentScan            // 扫描当前包及子包的 @Component
public @interface SpringBootApplication {}

3. 自动装配流程

@EnableAutoConfiguration


@Import(AutoConfigurationImportSelector.class)


selectImports()


SpringFactoriesLoader.loadFactoryNames()
   读取 META-INF/spring/
   org.springframework.boot.autoconfigure.AutoConfiguration.imports


加载所有 xxxAutoConfiguration 类


@Conditional 条件过滤
   @ConditionalOnClass       // classpath 存在指定类
   @ConditionalOnMissingBean // 容器中不存在指定 Bean
   @ConditionalOnProperty    // 配置文件中存在指定属性


满足条件的配置类生效,注册 Bean 到 Spring 容器

4. 源码核心实现

// AutoConfigurationImportSelector.java 核心方法
protected List<String> getCandidateConfigurations(
        AnnotationMetadata metadata, AnnotationAttributes attributes) {

    // SpringBoot 3.x 从 imports 文件加载
    List<String> configurations = ImportCandidates
        .load(AutoConfiguration.class, getBeanClassLoader())
        .getCandidates();

    Assert.notEmpty(configurations,
        "No auto configuration classes found in " +
        "META-INF/spring/org.springframework.boot..." +
        "Did you forget to add your own AutoConfiguration?");
    return configurations;
}

5. 自定义 Starter 实战

5.1 创建自动配置类

@AutoConfiguration
@ConditionalOnClass(Jedis.class)              // classpath 有 Jedis 才生效
@EnableConfigurationProperties(RedisProperties.class)  // 绑定配置
public class MyRedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                 // 用户没有自定义才生效
    public Jedis jedis(RedisProperties props) {
        return new Jedis(props.getHost(), props.getPort());
    }
}

5.2 注册自动配置

resources/META-INF/spring/ 下创建:

# org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.example.MyRedisAutoConfiguration

6. 面试高频问题

Q:SpringBoot 如何知道要加载哪些自动配置类?

A:通过 AutoConfigurationImportSelector 读取 classpath 下所有 jar 包内的 META-INF/spring/*.imports 文件,获取配置类全路径列表。

Q:条件注解的原理是什么?

A:@Conditional 注解接收一个 Condition 接口实现类,框架在注册 Bean 前调用 matches() 方法,返回 false 则跳过该 Bean。

💡 掌握自动装配原理,不仅能写出更优雅的 Spring 代码,还能轻松实现自研 Starter 框架!

💬 文章评论 (0)

支持 Markdown,请友善交流
正在加载评论...