这次我们来看一套完整的 SpringBoot 实战教程,特别适合需要快速上手 Java 微服务开发的初学者和面试准备者。这套教程号称"45分钟速通",重点不是概念堆砌,而是能不能在本地环境快速跑起来、理解核心配置、完成基础功能开发。
如果你关心 SpringBoot 的实际部署、项目结构、自动配置原理、接口开发、数据库整合和微服务架构基础,这篇文章可以直接收藏。我们会从环境准备开始,完成一个可运行的 SpringBoot 项目,测试基础接口,整合 MyBatis 操作数据库,最后讨论微服务架构的核心要点。
本文适合有一定 Java 基础但 SpringBoot 经验不多的开发者,或者需要复习 SpringBoot 核心知识的面试准备者。我们将使用 IntelliJ IDEA 作为开发工具,MySQL 作为数据库,Maven 进行依赖管理。
1. SpringBoot 核心能力速览
| 能力项 | 说明 |
|---|---|
| 学习门槛 | 需要基本 Java 基础,了解 MVC 概念更佳 |
| 开发工具 | IntelliJ IDEA(社区版即可) |
| 依赖管理 | Maven 或 Gradle |
| 内嵌服务器 | Tomcat(默认)、Jetty、Undertow |
| 启动方式 | 主类直接运行、命令行 mvn spring-boot:run |
| 配置方式 | application.properties/yml 自动加载 |
| 数据库支持 | MySQL、PostgreSQL、H2 等,整合 MyBatis/JPA |
| 微服务能力 | Spring Cloud 生态基础,服务发现、配置中心 |
| 适合场景 | 快速原型开发、微服务入门、企业级应用基础 |
SpringBoot 最大的优势是"约定大于配置",大部分通用配置已经预设好,开发者只需关注业务逻辑。下面我们通过实际项目来验证这些能力。
2. SpringBoot 适用场景与使用边界
SpringBoot 特别适合以下场景:
- 快速原型开发:内嵌 Tomcat 和自动配置让项目能在几分钟内启动运行
- 微服务入门:为后续学习 Spring Cloud 提供技术基础
- 企业级应用:提供完整的生产就绪功能(健康检查、指标监控等)
- 面试准备:覆盖大部分 Java 后端面试的 SpringBoot 相关问题
但不适合:
- 超简单静态网站:过度工程化,轻量级框架更合适
- 性能极致要求的场景:内嵌服务器和自动配置有一定开销
- 完全自定义的架构:SpringBoot 的约定可能限制特殊需求
在使用过程中要注意代码规范和企业级开发的最佳实践,避免因快速开发而忽视软件质量。
3. 环境准备与前置条件
开始前请确保本地环境满足以下要求:
操作系统要求
- Windows 10/11、macOS 10.14+ 或 Linux Ubuntu 18.04+
- 至少 8GB 内存,推荐 16GB
- 至少 10GB 可用磁盘空间
开发工具安装
- JDK 17(长期支持版本)
# 验证安装 java -version javac -version- IntelliJ IDEA(社区版或旗舰版)
- 社区版:免费,基础功能完整
- 旗舰版:提供 Spring 初始化和数据库工具
- Maven 3.6+
# 验证安装 mvn -v- MySQL 8.0+
- 安装 MySQL 服务器
- 配置 root 密码
- 创建测试数据库
环境变量配置
- JAVA_HOME 指向 JDK 安装目录
- MAVEN_HOME 指向 Maven 安装目录
- PATH 包含 %JAVA_HOME%\bin 和 %MAVEN_HOME%\bin
4. 创建第一个 SpringBoot 项目
我们使用 Spring Initializr 快速生成项目骨架。
通过 IDEA 创建
打开 IDEA → New Project → Spring Initializr
选择项目信息:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.0+(推荐)
- Group: com.example
- Artifact: demo
- Package: com.example.demo
选择依赖:
- Spring Web(Web 功能)
- Spring Boot DevTools(热部署)
- Lombok(简化代码)
生成项目并导入 IDEA
项目结构说明
demo/ ├── src/ │ ├── main/ │ │ ├── java/com/example/demo/ │ │ │ ├── DemoApplication.java # 主启动类 │ │ │ └── controller/ # 控制器层 │ │ └── resources/ │ │ ├── application.properties # 配置文件 │ │ └── static/ # 静态资源 │ └── test/ # 测试代码 ├── pom.xml # Maven 配置 └── target/ # 编译输出验证项目启动找到DemoApplication.java,右键运行:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }启动成功后控制台显示:
Tomcat started on port(s): 8080 (http) Started DemoApplication in 2.345 seconds访问 http://localhost:8080 应该看到 Whitelabel Error Page(正常,尚未定义首页)。
5. 基础功能开发与测试
5.1 创建第一个 REST 接口
在controller包下创建HelloController.java:
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello(@RequestParam(value = "name", defaultValue = "World") String name) { return String.format("Hello %s!", name); } @GetMapping("/api/info") public ApiResponse getInfo() { return new ApiResponse("OK", "SpringBoot 服务运行正常"); } // 内部响应类 public static class ApiResponse { private String status; private String message; public ApiResponse(String status, String message) { this.status = status; this.message = message; } // getter/setter 省略,实际使用 Lombok @Data } }接口测试启动服务后测试:
# 测试基础接口 curl "http://localhost:8080/hello" curl "http://localhost:8080/hello?name=SpringBoot" # 测试 JSON 接口 curl "http://localhost:8080/api/info"5.2 配置 application.properties
在resources/application.properties中添加配置:
# 服务器配置 server.port=8080 server.servlet.context-path=/demo # 应用配置 spring.application.name=demo-app # 日志配置 logging.level.com.example.demo=DEBUG logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n # 开发配置 spring.devtools.restart.enabled=true spring.mvc.log-request-details=true重启服务,现在访问地址变为:http://localhost:8080/demo/hello
5.3 热部署测试
修改HelloController的返回信息,保存后观察控制台:
Restarting application... Started DemoApplication in 1.234 seconds无需手动重启,修改立即生效。
6. 数据库整合与 MyBatis 实战
6.1 数据库准备
在 MySQL 中执行:
CREATE DATABASE springboot_demo; USE springboot_demo; CREATE TABLE users ( id BIGINT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); INSERT INTO users (username, email) VALUES ('testuser', 'test@example.com'), ('admin', 'admin@example.com');6.2 添加数据库依赖
在pom.xml中添加:
<dependencies> <!-- 已有依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 新增数据库相关 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>6.3 配置数据源
application.properties新增:
# 数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo spring.datasource.username=root spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # MyBatis 配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity6.4 创建实体类和 Mapper
创建实体类User.java:
package com.example.demo.entity; import lombok.Data; import java.time.LocalDateTime; @Data public class User { private Long id; private String username; private String email; private LocalDateTime createdAt; }创建 Mapper 接口UserMapper.java:
package com.example.demo.mapper; import com.example.demo.entity.User; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface UserMapper { @Select("SELECT * FROM users") List<User> findAll(); @Select("SELECT * FROM users WHERE id = #{id}") User findById(Long id); @Insert("INSERT INTO users(username, email) VALUES(#{username}, #{email})") @Options(useGeneratedKeys = true, keyProperty = "id") int insert(User user); @Update("UPDATE users SET username=#{username}, email=#{email} WHERE id=#{id}") int update(User user); @Delete("DELETE FROM users WHERE id=#{id}") int delete(Long id); }6.5 创建用户服务接口
创建UserController.java:
package com.example.demo.controller; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserMapper userMapper; @GetMapping public List<User> getAllUsers() { return userMapper.findAll(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userMapper.findById(id); } @PostMapping public String createUser(@RequestBody User user) { userMapper.insert(user); return "用户创建成功"; } @PutMapping("/{id}") public String updateUser(@PathVariable Long id, @RequestBody User user) { user.setId(id); userMapper.update(user); return "用户更新成功"; } @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { userMapper.delete(id); return "用户删除成功"; } }6.6 数据库接口测试
使用 curl 或 Postman 测试:
# 查询所有用户 curl "http://localhost:8080/demo/api/users" # 根据ID查询用户 curl "http://localhost:8080/demo/api/users/1" # 创建新用户 curl -X POST "http://localhost:8080/demo/api/users" \ -H "Content-Type: application/json" \ -d '{"username":"newuser","email":"new@example.com"}' # 更新用户 curl -X PUT "http://localhost:8080/demo/api/users/1" \ -H "Content-Type: application/json" \ -d '{"username":"updated","email":"updated@example.com"}' # 删除用户 curl -X DELETE "http://localhost:8080/demo/api/users/3"7. 微服务架构核心概念理解
7.1 什么是微服务架构
微服务架构是将单一应用程序划分成一组小服务的开发方法,每个服务运行在自己的进程中,服务之间通过轻量级机制(通常是 HTTP API)通信。
SpringBoot 在微服务中的角色
- 每个微服务是一个独立的 SpringBoot 应用
- 提供内嵌服务器,无需外部 Tomcat
- 自动配置简化服务开发
- 与 Spring Cloud 生态无缝集成
7.2 微服务核心组件
| 组件 | 作用 | SpringBoot 整合 |
|---|---|---|
| 服务注册发现 | 服务动态注册和发现 | Eureka、Consul |
| 配置中心 | 统一管理配置 | Spring Cloud Config |
| API 网关 | 统一入口、路由、过滤 | Spring Cloud Gateway |
| 负载均衡 | 请求分发 | Ribbon、LoadBalancer |
| 熔断器 | 服务降级、容错 | Hystrix、Resilience4j |
7.3 简单微服务示例
创建两个独立的 SpringBoot 项目:
用户服务 (user-service)
@RestController @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { // 查询用户信息 return userService.findById(id); } }订单服务 (order-service)
@RestController @RequestMapping("/orders") public class OrderController { @Autowired private RestTemplate restTemplate; @GetMapping("/user/{userId}") public List<Order> getOrdersByUser(@PathVariable Long userId) { // 调用用户服务获取用户信息 User user = restTemplate.getForObject( "http://user-service/users/{userId}", User.class, userId ); // 查询用户订单 return orderService.findByUser(user); } }8. 生产环境配置与优化
8.1 多环境配置
创建不同的配置文件:
application-dev.properties(开发环境)application-test.properties(测试环境)application-prod.properties(生产环境)
通过启动参数指定环境:
java -jar demo.jar --spring.profiles.active=prod8.2 健康检查与监控
SpringBoot Actuator 提供生产就绪功能:
在pom.xml添加:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>配置application.properties:
# Actuator 配置 management.endpoints.web.exposure.include=health,info,metrics management.endpoint.health.show-details=always # 自定义健康检查 management.health.diskspace.enabled=true访问监控端点:
- http://localhost:8080/demo/actuator/health
- http://localhost:8080/demo/actuator/info
- http://localhost:8080/demo/actuator/metrics
8.3 日志配置优化
生产环境日志配置:
# 日志文件输出 logging.file.name=app.log logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n # 按大小滚动日志 logging.logback.rollingpolicy.max-file-size=10MB logging.logback.rollingpolicy.max-history=30 # 不同包的不同日志级别 logging.level.com.example.demo=INFO logging.level.org.springframework.web=WARN9. 常见问题与排查方法
| 问题现象 | 可能原因 | 排查方式 | 解决方案 |
|---|---|---|---|
| 启动时报端口占用 | 8080 端口被其他进程占用 | netstat -ano | findstr 8080 | 修改 server.port 或终止占用进程 |
| 数据库连接失败 | 密码错误、网络不通、服务未启动 | 检查 MySQL 服务状态和连接字符串 | 验证配置,确保数据库可访问 |
| 依赖下载失败 | Maven 仓库网络问题 | 检查 Maven settings.xml | 配置国内镜像源 |
| 热部署不生效 | DevTools 配置问题 | 检查 IDEA 自动编译设置 | File → Settings → Build → Compiler → Build project automatically |
| 404 错误 | 路径错误或控制器未扫描 | 检查 @SpringBootApplication 扫描范围 | 确保控制器在主类同级或子包 |
| 静态资源访问不到 | 资源路径配置错误 | 检查 static 目录位置 | 资源应放在 src/main/resources/static |
| MyBatis 映射失败 | 配置路径错误或注解问题 | 检查 mapper-locations 和 @Mapper | 确保 XML 文件在正确路径 |
9.1 内存溢出处理
常见错误:java.lang.OutOfMemoryError: Java heap space
解决方案:
- 增加 JVM 内存参数:
java -Xms512m -Xmx1024m -jar demo.jar- 分析内存使用:
# 查看内存状态 jstat -gc <pid> 1000- 使用 VisualVM 或 JProfiler 分析内存泄漏
9.2 性能优化建议
- 连接池配置
# HikariCP 连接池配置 spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.idle-timeout=300000- JSON 序列化优化
@Configuration public class WebConfig { @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); return new MappingJackson2HttpMessageConverter(mapper); } }- 静态资源缓存
# 缓存静态资源 spring.web.resources.cache.cachecontrol.max-age=3600 spring.web.resources.cache.cachecontrol.public=true10. 学习路线与进阶方向
10.1 SpringBoot 深入学习路径
基础掌握(本文覆盖)
- 项目创建和启动
- REST API 开发
- 数据库整合
- 基础配置
中级进阶
- 安全控制(Spring Security)
- 缓存技术(Redis)
- 消息队列(RabbitMQ)
- 任务调度(@Scheduled)
高级应用
- 微服务架构(Spring Cloud)
- 分布式事务
- 容器化部署(Docker)
- 性能监控和调优
10.2 面试重点准备
常见面试题方向:
- SpringBoot 自动配置原理
- Starter 的作用和实现机制
- 内嵌容器的优势和原理
- 如何自定义 Starter
- SpringBoot 与 Spring MVC 的关系
- 配置文件加载优先级
- 条件注解的使用场景
实战问题:
- 如何设计一个完整的 RESTful API?
- 数据库事务如何管理?
- 如何进行单元测试和集成测试?
- 如何部署到生产环境?
10.3 项目实战建议
从简单项目开始
- 个人博客系统
- 待办事项应用
- 简单的 CRM 系统
逐步添加复杂度
- 添加用户认证和授权
- 集成第三方 API
- 实现文件上传下载
- 添加缓存和搜索功能
生产级考虑
- 错误处理和日志记录
- 性能监控和健康检查
- 安全防护和 SQL 注入预防
- 数据库迁移和版本控制
这套 SpringBoot 教程的核心价值在于实战导向,通过实际代码演示让学习者快速理解框架的核心概念。建议按照文章步骤实际操作,遇到问题时参考排查方法,逐步积累开发经验。
SpringBoot 作为现代 Java 开发的事实标准,掌握其核心用法对职业发展至关重要。下一步可以深入 Spring Cloud 微服务生态,或者学习前端框架实现全栈开发能力。