Spring Boot 速查表
本文档提供 Spring Boot 常用配置、注解和命令的快速参考。
项目创建
Spring Initializr
# Web 界面
https://start.spring.io/
# 命令行创建
curl https://start.spring.io/starter.zip \
-d type=maven-project \
-d language=java \
-d bootVersion=3.2.0 \
-d groupId=com.example \
-d artifactId=demo \
-d javaVersion=17 \
-d dependencies=web,data-jpa,mysql \
-o demo.zip
常用起步依赖
| 依赖 | 说明 |
|---|---|
spring-boot-starter-web | Web 开发 |
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 | 测试框架 |
spring-boot-starter-aop | AOP 支持 |
spring-boot-starter-mail | 邮件发送 |
spring-boot-starter-amqp | 消息队列 |
mybatis-spring-boot-starter | MyBatis 集成 |
常用配置
application.yml
# 服务器配置
server:
port: 8080
servlet:
context-path: /api
# 应用配置
spring:
application:
name: my-app
# 数据源配置
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
# JPA 配置
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
# Redis 配置
data:
redis:
host: localhost
port: 6379
password:
database: 0
# 文件上传
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB
# JSON 配置
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
default-property-inclusion: non_null
# 缓存配置
cache:
type: redis
# 日志配置
logging:
level:
root: info
com.example: debug
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
# Actuator 配置
management:
endpoints:
web:
exposure:
include: health,info,metrics
endpoint:
health:
show-details: always
核心注解
启动类注解
@SpringBootApplication // 组合注解
@SpringBootConfiguration // 配置类
@EnableAutoConfiguration // 自动配置
@ComponentScan // 组件扫描
Web 注解
// 控制器
@RestController // REST 控制器
@Controller // Web 控制器
@RequestMapping("/api") // 路径映射
// HTTP 方法
@GetMapping // GET 请求
@PostMapping // POST 请求
@PutMapping // PUT 请求
@DeleteMapping // DELETE 请求
@PatchMapping // PATCH 请求
// 参数绑定
@RequestParam // 查询参数
@PathVariable // 路径变量
@RequestBody // 请求体
@RequestHeader // 请求头
@CookieValue // Cookie 值
// 响应
@ResponseBody // 响应体
@ResponseStatus // 响应状态码
数据访问注解
// JPA
@Entity // 实体类
@Table(name = "t_user") // 表名
@Id // 主键
@GeneratedValue // 主键生成
@Column // 字段映射
@OneToOne // 一对一
@OneToMany // 一对多
@ManyToOne // 多对一
@ManyToMany // 多对多
// Repository
@Repository // Repository 类
@Transactional // 事务
验证注解
@NotNull // 不能为 null
@NotBlank // 不能为空字符串
@NotEmpty // 不能为空
@Size(min, max) // 长度范围
@Min(value) // 最小值
@Max(value) // 最大值
@Email // 邮箱格式
@Pattern(regexp) // 正则匹配
@Past // 过去日期
@Future // 未来日期
@Digits(integer, fraction) // 数字位数
@Valid // 嵌套验证
配置注解
@Configuration // 配置类
@Bean // Bean 定义
@Value("${property}") // 属性注入
@ConfigurationProperties // 属性绑定
@PropertySource // 属性文件
@Profile // 环境配置
条件注解
@ConditionalOnClass // 类存在时
@ConditionalOnMissingClass // 类不存在时
@ConditionalOnBean // Bean 存在时
@ConditionalOnMissingBean // Bean 不存在时
@ConditionalOnProperty // 属性满足条件时
@ConditionalOnWebApplication // Web 应用时
@ConditionalOnExpression // SpEL 为 true 时
AOP 注解
@Aspect // 切面类
@Pointcut // 切入点
@Before // 前置通知
@After // 后置通知
@AfterReturning // 返回通知
@AfterThrowing // 异常通知
@Around // 环绕通知
常用命令
Maven 命令
# 编译
mvn compile
# 打包
mvn package
# 跳过测试打包
mvn package -DskipTests
# 运行
mvn spring-boot:run
# 清理
mvn clean
# 清理并打包
mvn clean package
# 安装到本地仓库
mvn install
# 查看依赖树
mvn dependency:tree
# 运行测试
mvn test
Gradle 命令
# 编译
gradle build
# 运行
gradle bootRun
# 清理
gradle clean
# 打包
gradle bootJar
# 运行测试
gradle test
# 查看依赖
gradle dependencies
JAR 运行
# 运行 JAR
java -jar app.jar
# 指定端口
java -jar app.jar --server.port=9090
# 指定环境
java -jar app.jar --spring.profiles.active=prod
# 指定配置文件
java -jar app.jar --spring.config.location=/path/to/application.yml
# 后台运行
nohup java -jar app.jar > app.log 2>&1 &
RESTful API 设计规范
HTTP 方法
| 方法 | 操作 | 成功响应码 |
|---|---|---|
| GET | 查询 | 200 OK |
| POST | 创建 | 201 Created |
| PUT | 更新(完整) | 200 OK |
| PATCH | 更新(部分) | 200 OK |
| DELETE | 删除 | 204 No Content |
URL 设计
# 推荐
GET /api/users # 获取用户列表
GET /api/users/{id} # 获取单个用户
POST /api/users # 创建用户
PUT /api/users/{id} # 更新用户
DELETE /api/users/{id} # 删除用户
# 不推荐
GET /api/getUsers
POST /api/createUser
DELETE /api/deleteUser?id=1
响应状态码
| 状态码 | 说明 |
|---|---|
| 200 | 成功 |
| 201 | 创建成功 |
| 204 | 成功(无内容) |
| 400 | 请求参数错误 |
| 401 | 未授权 |
| 403 | 禁止访问 |
| 404 | 资源不存在 |
| 409 | 冲突 |
| 500 | 服务器错误 |
统一响应格式
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
private Integer code;
private String message;
private T data;
public static <T> Result<T> success(T data) {
return new Result<>(200, "success", data);
}
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
}
异常处理模板
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleValidation(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(", "));
return Result.error(400, message);
}
@ExceptionHandler(BusinessException.class)
public Result<Void> handleBusiness(BusinessException e) {
return Result.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
return Result.error(500, "系统错误");
}
}
分页查询
// Controller
@GetMapping
public Result<Page<User>> list(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size
) {
Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
return Result.success(userRepository.findAll(pageable));
}
配置属性绑定
@Data
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private boolean enabled = true;
private List<String> servers;
private Duration timeout;
}
app:
name: my-app
enabled: true
servers:
- server1.example.com
- server2.example.com
timeout: 30s
测试注解
@SpringBootTest // Spring Boot 测试
@WebMvcTest // MVC 测试
@DataJpaTest // JPA 测试
@AutoConfigureMockMvc // 配置 MockMvc
@MockBean // Mock Bean
@TestConfiguration // 测试配置
@Import // 导入配置
Actuator 端点
| 端点 | 说明 |
|---|---|
/actuator/health | 健康检查 |
/actuator/info | 应用信息 |
/actuator/metrics | 指标信息 |
/actuator/env | 环境变量 |
/actuator/beans | Bean 列表 |
/actuator/mappings | 路径映射 |
/actuator/threaddump | 线程转储 |
/actuator/heapdump | 堆转储 |
常见问题解决
端口被占用
# Windows
netstat -ano | findstr :8080
taskkill /PID <PID> /F
# Linux/macOS
lsof -i :8080
kill -9 <PID>
# 或修改端口
server.port=8081
依赖冲突
# 查看依赖树
mvn dependency:tree
# 排除冲突依赖
<dependency>
<groupId>com.example</groupId>
<artifactId>some-lib</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
乱码问题
server:
servlet:
encoding:
charset: UTF-8
enabled: true
force: true
时区问题
spring:
jackson:
time-zone: GMT+8
datasource:
url: jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
推荐配置模板
开发环境
server:
port: 8080
spring:
profiles:
active: dev
datasource:
url: jdbc:mysql://localhost:3306/mydb_dev
username: root
password: root
logging:
level:
com.example: debug
debug: true
生产环境
server:
port: 80
spring:
datasource:
url: jdbc:mysql://prod-db:3306/mydb
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
logging:
level:
root: warn
management:
endpoints:
web:
exposure:
include: health,info,metrics