Skip to content

Spring Boot 自动配置

Spring Boot 核心优势

┌─────────────────────────────────────────────────────────────────┐
│                    Spring Boot vs Spring                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Spring                     Spring Boot                         │
│  ──────                    ─────────────                        │
│  配置繁琐                    自动配置                             │
│  依赖管理复杂                 起步依赖管理                        │
│  服务器手动部署               内嵌服务器                           │
│  版本兼容难                   自动版本仲裁                         │
│  大量 XML 配置               零 XML 配置                         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

自动配置原理

@SpringBootApplication

java
@SpringBootApplication
// 等价于:
@Configuration          // 标注为配置类
@EnableAutoConfiguration // 启用自动配置
@ComponentScan          // 组件扫描
public class Application { }

自动配置流程

┌─────────────────────────────────────────────────────────────────┐
│                    自动配置执行流程                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. Spring Boot 启动,加载 spring-boot-autoconfigure.jar        │
│            ↓                                                     │
│  2. @EnableAutoConfiguration 触发                               │
│            ↓                                                     │
│  3. SpringFactoriesLoader 加载 META-INF/spring.factories        │
│            ↓                                                     │
│  4. 根据条件 @Conditional 筛选要启用的配置类                      │
│            ↓                                                     │
│  5. 通过 @Bean 注册配置类中的组件                                 │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

spring.factories

properties
# 文件位置:META-INF/spring.factories
# Spring Boot 2.7+ 使用 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

条件装配

常用条件注解

注解说明
@ConditionalOnClass类路径存在某类时才配置
@ConditionalOnMissingClass类路径不存在某类时才配置
@ConditionalOnProperty配置属性满足条件时才配置
@ConditionalOnBean容器中存在某 Bean 时才配置
@ConditionalOnMissingBean容器中不存在某 Bean 时才配置
@ConditionalOnWebApplication是 Web 应用时才配置
java
@Configuration
@ConditionalOnClass(DataSource.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().build();
    }
}

起步依赖(Starter)

原理

xml
<!-- spring-boot-starter-web 包含的依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
<!-- Tomcat 等服务器 -->

常用 Starter

Starter用途
spring-boot-starter-webWeb 开发
spring-boot-starter-data-jpaJPA 持久层
spring-boot-starter-data-redisRedis 缓存
spring-boot-starter-security安全认证
spring-boot-starter-test单元测试
spring-boot-starter-actuator应用监控

自定义 Starter

1. 创建自动配置模块

java
// MyAutoConfiguration.java
@Configuration
@ConditionalOnProperty(prefix = "myapp", name = "enabled", havingValue = "true")
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

2. 注册自动配置

properties
# META-INF/spring.factories (Spring Boot 2.7 之前)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyAutoConfiguration

# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (Spring Boot 2.7+)
com.example.MyAutoConfiguration

3. 使用 Starter

yaml
# application.yml
myapp:
  enabled: true

Spring Boot 配置

application.yml / application.properties

yaml
# application.yml 示例
spring:
  application:
    name: myapp
  profiles:
    active: dev

server:
  port: 8080
  servlet:
    context-path: /api

logging:
  level:
    com.example: DEBUG

多环境配置

src/
├── application.yml          # 公共配置
├── application-dev.yml      # 开发环境
├── application-test.yml     # 测试环境
└── application-prod.yml     # 生产环境

@ConfigurationProperties

java
// 配置绑定
@Component
@ConfigurationProperties(prefix = "app.user")
public class UserProperties {
    private String name;
    private int age;
    private String email;

    // getters and setters
}

// application.yml
// app:
//   user:
//     name: 张三
//     age: 25
//     email: zhangsan@example.com

常用注解

java
// Spring Boot 应用
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// 配置类
@Configuration
@ComponentScan("com.example")
@PropertySource("classpath:config.properties")

// 条件装配
@ConditionalOnClass(RedisOperations.class)
@ConditionalOnProperty(prefix = "spring.redis", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(RedisProperties.class)

// 懒加载
@Lazy

// 跨域配置
@CrossOrigin(origins = "http://example.com")

SpringApplication

定制启动行为

java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);

        // 关闭 Banner
        app.setBannerMode(Banner.Mode.OFF);

        // 添加监听器
        app.addListeners(new MyApplicationListener());

        // 禁用 Web 环境
        // app.setWebApplicationType(WebApplicationType.NONE);

        ConfigurableApplicationContext ctx = app.run(args);
    }
}

事件监听

java
// 应用启动事件
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("应用已启动");
    }
}

总结

Spring Boot 核心知识点

知识点面试频率实战重要性
自动配置原理⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
@Conditional 条件装配⭐⭐⭐⭐⭐⭐⭐⭐
起步依赖原理⭐⭐⭐⭐⭐⭐⭐
自定义 Starter⭐⭐⭐⭐⭐⭐
多环境配置⭐⭐⭐⭐⭐⭐⭐⭐

⚠️ 易错点提醒

  1. Spring Boot 2.7+ 使用 AutoConfiguration.imports 替代 spring.factories
  2. 自定义 Starter 命名规范:xxx-spring-boot-starter
  3. @ConditionalOnMissingBean 用于用户自定义 Bean 优先
  4. 配置属性用 @ConfigurationProperties 更类型安全
  5. 生产环境记得禁用 debug=true 和管理端点