Spring Boot 入门
一、Spring Boot 是什么
Spring Boot 是 Spring 的脚手架,约定优于配置,让你快速搭建 Spring 应用。
┌─────────────────────────────────────────────────────────────┐
│ 传统 Spring │
├─────────────────────────────────────────────────────────────┤
│ 1. 手动添加各种依赖(版本冲突头疼) │
│ 2. 编写大量 XML 配置或 Java Config │
│ 3. 部署到 Tomcat/Jetty 等容器 │
│ 4. 打包成 WAR 文件 │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Spring Boot │
├─────────────────────────────────────────────────────────────┤
│ 1. starter 依赖统一管理(自动版本仲裁) │
│ 2. 自动配置(@EnableAutoConfiguration) │
│ 3. 内嵌 Tomcat/Jetty/Undertow(直接 java -jar 运行) │
│ 4. 打包成 JAR,内嵌容器 │
│ 5. 运维监控(Actuator) │
│ 6. 简化配置(application.yml) │
└─────────────────────────────────────────────────────────────┘二、快速开始
方式一:Spring Initializr(推荐)
访问 https://start.spring.io/ 或 IDEA 创建:
Project: Maven / Gradle
Language: Java 17+
Spring Boot: 3.2.x
Group: com.example
Artifact: demo
Dependencies: Spring Web, Spring Data JPA, MySQL Driver方式二:手动创建
1. pom.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>2. 主类
java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}3. 写一个 Controller
java
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}4. 运行
bash
# Maven 方式
mvn spring-boot:run
# 或先打包再运行
mvn package
java -jar target/demo-1.0.0.jar三、Spring Boot 执行流程
┌─────────────────────────────────────────────────────────────────┐
│ SpringApplication.run() │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. 创建 SpringApplication 对象 │
│ ├─ 推断应用类型(Servlet/Reactive/None) │
│ ├─ 初始化 initializer │
│ └─ 初始化 listener │
│ │
│ 2. 执行 run() 方法 │
│ ├─ 创建 BootstrapContext(引导上下文) │
│ ├─ 配置 Headless 属性 │
│ ├─ 获取并运行 SpringApplicationRunListeners │
│ │ │
│ ├─ 创建 Environment │
│ │ ├─ 加载 application.properties/yml │
│ │ └─ 设置 profile │
│ │ │
│ ├─ 打印 Banner(启动横幅) │
│ │ │
│ ├─ 创建 ApplicationContext │
│ │ └─ 推断 Web 类型 │
│ │ │
│ ├─ prepareContext() │
│ │ ├─ 加载 Bean 定义 │
│ │ └─ 加载 Configuration 类的 @Bean │
│ │ │
│ ├─ refreshContext() ← 核心!!! │
│ │ └─ 真正启动 Spring 容器 │
│ │ │
│ └─ 执行 runners │
│ └─ ApplicationRunner, CommandLineRunner │
│ │
└─────────────────────────────────────────────────────────────────┘四、自动配置原理
@SpringBootApplication 分解
java
@SpringBootConfiguration // 等价于 @Configuration
@EnableAutoConfiguration // 启用自动配置
@ComponentScan // 组件扫描
public @interface SpringBootApplication { }@EnableAutoConfiguration
java
@AutoConfigurationPackage // 标记自动配置类所在包
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
Class<?>[] exclude() default {}; // 排除的配置
String[] excludeName() default {};
}自动配置流程
┌─────────────────────────────────────────────────────────────────┐
│ 自动配置流程 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Spring Factories 机制 │
│ └─ META-INF/spring.factories │
│ └─ org.springframework.boot.autoconfigure.EnableAutoConfiguration
│ └─ 列出所有自动配置类 │
│ │
│ 1. Spring Boot 启动时扫描所有 jar 的 spring.factories │
│ │
│ 2. 加载 @AutoConfiguration 标注的配置类 │
│ @Configuration │
│ @ConditionalOnClass(DataSource.class) // 条件判断 │
│ @ConditionalOnProperty(prefix="spring.datasource",...) │
│ public class DataSourceAutoConfiguration { } │
│ │
│ 3. 使用 @Bean 定义组件 │
│ │
│ 4. 用户配置覆盖默认配置 │
│ │
└─────────────────────────────────────────────────────────────────┘常用自动配置类
| 配置类 | 条件 | 功能 |
|---|---|---|
| DataSourceAutoConfiguration | classpath有数据源 | 自动配置 DataSource |
| WebMvcAutoConfiguration | 是 Web 应用 | 自动配置 MVC |
| 事务 | ||
| JdbcTemplateAutoConfiguration | 自动配置 JdbcTemplate | |
| ErrorMvcAutoConfiguration | 自动配置异常处理 |
排除自动配置
java
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class App { }
// 或
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration五、starter 依赖
starter 命名规范
spring-boot-starter-xxx # 官方 starter
xxx-spring-boot-starter # 第三方 starter常用 starter
| starter | 用途 |
|---|---|
| spring-boot-starter-web | Web 开发(含 MVC、Tomcat) |
| spring-boot-starter-data-jpa | JPA 数据访问 |
| spring-boot-starter-data-redis | Redis 访问 |
| spring-boot-starter-security | 安全认证 |
| spring-boot-starter-validation | 参数校验 |
| spring-boot-starter-actuator | 运维监控 |
| spring-boot-starter-test | 单元测试 |
第三方 starter
| starter | 来源 |
|---|---|
| mybatis-spring-boot-starter | MyBatis |
| druid-spring-boot-starter | Druid 连接池 |
| lombok | Lombok 工具 |
| spring-boot-starter-quartz | 定时任务 |
starter 依赖树
spring-boot-starter-web
│
├─ spring-boot-starter
│ └─ spring-boot-logging
│ └─ logback-classic
│ └─ logback-core
│
├─ spring-boot-starter-tomcat
│ └─ tomcat-embed-core
│
└─ spring-web
└─ spring-webmvc
└─ spring-context
└─ spring-aop
└─ spring-beans
└─ spring-core六、配置文件
application.properties 优先级
命令行参数 > 外置 application-{profile}.properties > 外置 application.properties > 内置 application.properties多环境配置
properties
# application-dev.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/dev
# application-prod.properties
server.port=80
spring.datasource.url=jdbc:mysql://prod:3306/prod
# application.yml
spring:
profiles:
active: devYAML 配置
yaml
server:
port: 8080
servlet:
context-path: /api
spring:
application:
name: demo-app
profiles:
active: dev
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
logging:
level:
com.example: DEBUG
org.springframework: INFO配置绑定
java
// 方式1:@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "person")
public class PersonProperties {
private String name;
private int age;
private List<String> hobbies;
private Map<String, String> phone;
// getters/setters
}
# application.yml
person:
name: 张三
age: 18
hobbies: [篮球, 足球]
phone:
home: 123456
mobile: 654321java
// 方式2:@EnableConfigurationProperties
@SpringBootApplication
@EnableConfigurationProperties(PersonProperties.class)
public class App { }
// 方式3:@ConfigurationProperties + @Bean
@Configuration
public class Config {
@Bean
@ConfigurationProperties(prefix = "person")
public PersonProperties personProperties() {
return new PersonProperties();
}
}七、banner 与 logo
禁用 banner
java
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
// 或
SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
builder.bannerMode(Banner.Mode.OFF).run(args);自定义 banner
创建 src/main/resources/banner.txt:
_____ _____ _____ _____ _____
|_ _| ____/ ___|_ _| ____|_ __
| | | _| \___ \ | | | _| \ \ / /
| | | |___ ___) || | | |___ \ V /
|_| |_____|____/ |_| |_____| \_/
${application.title} ${application.version}
Powered by Spring Boot ${spring-boot.version}banner.txt 变量:
| 变量 | 说明 |
|---|---|
| $ | 应用版本 |
| $ | 应用标题 |
| $ | Spring Boot 版本 |
| $ | 带括号版本 |
| $ | 带括号应用版本 |
八、Spring Boot 常用注解
核心注解
java
@SpringBootApplication // 主类标记
@Configuration // 配置类
@ComponentScan // 组件扫描
@EnableAutoConfiguration // 启用自动配置Bean 注解
java
@Bean // 定义 Bean
@Repository // DAO 层
@Service // 服务层
@Controller // 控制器
@RestController // REST 控制器
@RequiredArgsConstructor // Lombok 生成构造器(final 字段)
@Autowired // 依赖注入
@Qualifier // 指定 Bean 名称
@Primary // 默认实现优先配置注解
java
@Configuration // 配置类
@ConfigurationProperties // 配置属性绑定
@EnableConfigurationProperties // 启用配置属性
@PropertySource // 加载额外配置文件
@Import // 导入配置类
@Conditional // 条件装配请求注解
java
@GetMapping // GET 请求
@PostMapping // POST 请求
@PutMapping // PUT 请求
@DeleteMapping // DELETE 请求
@RequestMapping // 通用请求映射
@RequestParam // 请求参数
@RequestBody // 请求体
@PathVariable // 路径变量
@RequestHeader // 请求头
@CookieValue // Cookie校验注解
java
@Valid // 启动校验
@Validated // 分组校验
@NotNull // 非空
@NotBlank // 非空字符串
@NotEmpty // 非空集合
@Size // 长度限制
@Min / @Max // 数值范围
@Email // 邮箱格式
@Pattern // 正则表达式异常注解
java
@ControllerAdvice // 全局控制器增强
@ExceptionHandler // 异常处理方法
@ResponseStatus // 响应状态码九、静态资源
默认静态资源目录
classpath:/static/
classpath:/public/
classpath:/resources/
classpath:/META-INF/resources/自定义静态资源
yaml
spring:
web:
resources:
static-locations: classpath:/my-static/
add-mappings: true
cache:
period: 3600拦截器配置
java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/login", "/api/public/**");
}
}十、面试高频问题
Q1: Spring Boot 和 Spring 什么关系?
- Spring Boot 是 Spring 的脚手架/工具
- 基于 Spring Framework
- 简化了配置,内嵌容器
- 自动配置替代手动配置
Q2: Spring Boot 自动配置原理?
@EnableAutoConfiguration启用自动配置AutoConfigurationImportSelector加载spring.factories- 根据条件
@Conditional筛选配置类 - 使用
@Bean注册组件 - 用户配置优先覆盖
Q3: starter 的作用?
- 统一依赖版本管理(父 pom 管理)
- 一站式引入相关技术所需依赖
- 自动触发相关自动配置
Q4: Spring Boot 如何启动?
- 创建
SpringApplication对象 - 执行
run()方法 - 创建并刷新
ApplicationContext
Q5: Spring Boot 打包成 JAR 后如何运行?
- 使用 Maven/Gradle 插件打包
- JAR 内嵌 Tomcat/Jetty
java -jar xxx.jar直接运行
十一、下一章预告
下一章我们将深入学习 Spring Boot 自动配置原理:
- @EnableAutoConfiguration 详解
- @Conditional 条件装配
- 自定义 starter
- Spring Boot 内部原理