一、Spring Boot 简介
1. 什么是 Spring Boot?
Spring Boot:基于 Spring 框架的快速开发框架,通过约定优于配置、自动配置等特性,简化 Spring 应用的开发和部署。
2. Spring Boot 的核心价值
| 传统 Spring | Spring Boot | 优势 |
|---|---|---|
| 需要大量 XML 配置 | 自动配置 | 减少配置 |
| 手动创建 Bean | 约定优于配置 | 快速启动 |
| 部署复杂 | 内嵌服务器 | 简化部署 |
| 学习曲线陡峭 | 开箱即用 | 降低门槛 |
| 依赖管理复杂 | Starter 依赖 | 简化依赖 |
3. Spring Boot 的特性
| 特性 | 说明 |
|---|---|
| 自动配置 | 根据依赖自动装配 Bean |
| Starter 依赖 | 简化依赖管理 |
| 内嵌服务器 | 无需部署外部服务器 |
| 生产级特性 | 监控、健康检查、指标 |
| 无代码生成 | 无需生成代理代码 |
二、快速创建项目
1. 使用 Spring Initializr
访问: start.spring.io/
步骤:
- 选择项目类型(Maven/Gradle)
- 选择 Spring Boot 版本
- 填写项目信息(Group、Artifact)
- 添加依赖(Web、JPA、MySQL)
- 生成项目并下载
2. 命令行创建(Spring Boot CLI)
# 安装 Spring Boot CLI(可选)
curl -s "https://get.sdkman.io" | bash
sdk install springboot
# 创建项目
spring init --dependencies=web,data-jpa,mysql my-app
cd my-app
3. IDEA 创建项目
步骤:
- File → New → Project
- 选择 Spring Initializr
- 填写项目信息
- 选择依赖
- 创建项目
三、项目结构
1. 标准项目结构
my-app/
├── pom.xml # Maven 配置文件
└── src/
├── main/
│ ├── java/com/example/myapp/
│ │ ├── MyApplication.java # 启动类
│ │ ├── controller/ # 控制器层
│ │ ├── service/ # 服务层
│ │ ├── repository/ # 仓库层
│ │ ├── model/ # 实体类
│ │ ├── dto/ # 数据传输对象
│ │ ├── config/ # 配置类
│ │ └── exception/ # 异常处理
│ └── resources/
│ ├── application.properties # 配置文件
│ ├── static/ # 静态资源
│ └── templates/ # 模板文件
└── test/ # 测试代码
2. 启动类(MyApplication.java)
package com.example.myapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // 启用自动配置、组件扫描
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args); // 启动应用
}
}
@SpringBootApplication 注解解析:
@SpringBootConfiguration // 标记为配置类
@EnableAutoConfiguration // 启用自动配置(核心)
@ComponentScan // 扫描组件(@Component、@Service、@Repository)
public @interface SpringBootApplication {
// ...
}
四、第一个 Spring Boot 应用
1. 创建 Hello World Controller
HelloController.java:
package com.example.myapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // REST 控制器
public class HelloController {
@GetMapping("/hello") // GET /hello
public String hello() {
return "Hello, Spring Boot!";
}
}
2. 启动应用
方式 1:IDEA 运行
- 右键点击
MyApplication.java - 选择 Run 'MyApplication'
方式 2:Maven 命令
mvn spring-boot:run
方式 3:打包运行
mvn clean package
java -jar target/my-app-1.0.0.jar
3. 访问应用
打开浏览器访问:
http://localhost:8080/hello
响应:
Hello, Spring Boot!
五、配置文件
1. 配置文件格式
Spring Boot 支持两种配置文件格式:
| 格式 | 文件名 | 说明 |
|---|---|---|
| Properties | application.properties | 传统格式 |
| YAML | application.yml | 层级格式 |
2. application.properties 示例
# 服务器配置
server.port=8080
server.servlet.context-path=/api
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# 日志配置
logging.level.org.springframework.web=INFO
logging.level.com.example.myapp=DEBUG
3. application.yml 示例
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
logging:
level:
org.springframework.web: INFO
com.example.myapp: DEBUG
4. 读取配置值
方式 1:@Value 注解
@Component
public class AppConfig {
@Value("${app.name}")
private String appName;
@Value("${server.port}")
private int serverPort;
}
方式 2:@ConfigurationProperties
AppProperties.java:
@Component
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
private String name;
private String version;
private String description;
}
application.yml:
app:
name: My Application
version: 1.0.0
description: Spring Boot Demo
使用:
@Service
public class MyService {
@Autowired
private AppProperties appProperties;
public void printAppInfo() {
System.out.println("App Name: " + appProperties.getName());
System.out.println("Version: " + appProperties.getVersion());
}
}
六、依赖管理
1. Starter 依赖
什么是 Starter?
Starter 是 Spring Boot 提供的一组便捷依赖描述符,整合了相关依赖。
2. 常用 Starter 依赖
| Starter | 说明 | 包含依赖 |
|---|---|---|
spring-boot-starter-web | Web 应用开发 | Spring MVC、Tomcat |
spring-boot-starter-data-jpa | JPA 数据持久化 | Hibernate、Spring Data JPA |
spring-boot-starter-validation | 数据验证 | Hibernate Validator |
spring-boot-starter-security | 安全认证 | Spring Security |
spring-boot-starter-cache | 缓存支持 | Spring Cache |
spring-boot-starter-test | 测试支持 | JUnit、Mockito |
3. pom.xml 示例
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<dependencies>
<!-- Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
七、内嵌服务器
1. 默认服务器
Spring Boot 默认使用 Tomcat 作为内嵌服务器。
2. 切换服务器
切换到 Jetty
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除 Tomcat -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加 Jetty -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
切换到 Undertow
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除 Tomcat -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加 Undertow -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
3. 服务器配置
application.properties:
# 服务器端口
server.port=8080
# 服务器地址
server.address=0.0.0.0
# 上下文路径
server.servlet.context-path=/api
# 最大线程数
server.tomcat.threads.max=200
# 最小线程数
server.tomcat.threads.min-spare=10
八、Actuator 监控
1. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. 配置 Actuator
application.properties:
# 启用所有端点
management.endpoints.web.exposure.include=*
# 启用健康检查
management.endpoint.health.show-details=always
# 基础路径
management.endpoints.web.base-path=/actuator
3. 常用端点
| 端点 | URL | 说明 |
|---|---|---|
| 健康检查 | /actuator/health | 应用健康状态 |
| 信息 | /actuator/info | 应用信息 |
| 指标 | /actuator/metrics | 应用指标 |
| 环境 | /actuator/env | 环境变量 |
| 日志 | /actuator/loggers | 日志配置 |
4. 访问健康检查
curl http://localhost:8080/actuator/health
响应:
{
"status": "UP",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 107374182400,
"free": 53687091200,
"threshold": 10485760,
"exists": true
}
},
"ping": {
"status": "UP"
}
}
}
九、生产级特性
1. 健康检查
自定义健康检查:
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Autowired
private UserRepository userRepository;
@Override
public Health health() {
try {
long count = userRepository.count();
return Health.up()
.withDetail("userCount", count)
.build();
} catch (Exception e) {
return Health.down()
.withDetail("error", e.getMessage())
.build();
}
}
}
2. 指标
自定义指标:
@Component
public class CustomMetrics {
private final MeterRegistry registry;
public CustomMetrics(MeterRegistry registry) {
this.registry = registry;
}
public void recordUserRegistration() {
Counter.builder("user.registration.count")
.description("Number of user registrations")
.register(registry)
.increment();
}
}
3. 日志配置
application.yml:
logging:
level:
root: INFO
com.example.myapp: DEBUG
file:
name: logs/myapp.log
max-size: 10MB
max-history: 30
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
十、最佳实践
1. 包名规范
| 规范 | 示例 |
|---|---|
| 公司域名倒置 | com.example.myapp |
| 小写字母 | controller、service |
| 复数名词 | users、products |
2. 命名规范
| 类型 | 规范 | 示例 |
|---|---|---|
| 类名 | 大驼峰 | UserController |
| 方法名 | 小驼峰 | findById |
| 常量 | 全大写下划线 | MAX_SIZE |
| 包名 | 小写 | controller |
3. 分层架构
| 层 | 职责 |
|---|---|
| Controller | 接收请求,返回响应 |
| Service | 业务逻辑处理 |
| Repository | 数据访问 |
| Model | 实体映射 |
| DTO | 数据传输 |