Spring Boot是构建现代Java应用的事实标准框架,它简化了基于Spring的应用开发,提供了自动配置、独立运行和”约定优于配置”等特性。本教程将带您从零开始学习Spring Boot,涵盖环境搭建、核心概念、项目结构、常用功能以及实际开发中的最佳实践。
第一部分:环境准备与项目创建
1.1 开发环境要求
在开始Spring Boot开发前,需要准备以下环境:
- JDK 8或更高版本(推荐JDK 17或21)
- 构建工具:Maven 3.3+或Gradle 7.x+
- IDE:IntelliJ IDEA(推荐)、Eclipse或VS Code
- Spring Boot版本:3.x系列(当前最新3.2.x)
1.2 创建第一个Spring Boot项目
方式一:使用Spring Initializr(推荐)
- 访问 https://start.spring.io
- 选择项目配置:
- Project: Maven Project
- Language: Java
- Spring Boot: 3.2.5
- Group: com.example
- Artifact: demo
- Packaging: Jar
- Java: 17
- 添加依赖:Spring Web
- 点击”Generate”下载项目压缩包
方式二:使用命令行
curl https://start.spring.io/starter.tgz -d dependencies=web \
-d type=maven-project -d language=java -d bootVersion=3.2.5 \
-d groupId=com.example -d artifactId=demo -d name=demo \
-d description=Demo+project+for+Spring+Boot -d packageName=com.example.demo \
-d javaVersion=17 | tar -xzvf -
1.3 项目结构解析
解压后的项目包含以下核心文件和目录:
demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/demo/
│ │ │ └── DemoApplication.java # 主启动类
│ │ └── resources/
│ │ ├── static/ # 静态资源(js/css/images)
│ │ ├── templates/ # 模板文件(Thymeleaf等)
│ │ └── application.properties # 配置文件
│ └── test/ # 测试代码
├── pom.xml # Maven构建文件
└── .gitignore
第二部分:核心概念与基础开发
2.1 理解Spring Boot自动配置
Spring Boot的核心特性之一是自动配置,它基于:
- 类路径上的jar依赖
- 已定义的bean
- 各种属性设置
自动配置尝试智能地配置您的Spring应用。例如,当spring-webmvc
在类路径上时,Spring Boot会自动配置:
- DispatcherServlet
- 默认的视图解析器
- 静态资源处理
- 错误处理
2.2 编写第一个REST控制器
在com.example.demo
包下创建HelloController.java
:
package com.example.demo;
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 sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
2.3 运行应用
方式一:使用IDE
- 右键点击
DemoApplication.java
-> Run
方式二:使用Maven
mvn spring-boot:run
访问 http://localhost:8080/hello?name=Spring 将看到:
Hello Spring!
2.4 配置文件详解
Spring Boot支持多种配置方式,最常用的是application.properties
或application.yml
:
application.properties示例:
# 服务器端口配置
server.port=8081
# 应用名称
spring.application.name=demo-app
# 数据库配置示例
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
# JPA配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
等效的application.yml:
server:
port: 8081
spring:
application:
name: demo-app
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
show-sql: true
hibernate:
ddl-auto: update
第三部分:数据访问与持久层
3.1 集成Spring Data JPA
- 添加依赖到
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
- 创建实体类
User.java
:
package com.example.demo.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String email;
// 构造器、getter和setter省略
}
- 创建Repository接口
UserRepository.java
:
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
3.2 测试数据访问
创建DemoApplicationTests.java
测试类:
package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
void testUserRepository() {
User user = new User();
user.setName("John Doe");
user.setEmail("john@example.com");
userRepository.save(user);
User foundUser = userRepository.findByEmail("john@example.com");
assert(foundUser != null);
assert(foundUser.getName().equals("John Doe"));
}
}
第四部分:Web开发进阶
4.1 处理表单提交
创建UserController.java
处理用户相关请求:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/register")
public String showRegistrationForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String registerUser(@ModelAttribute User user) {
userRepository.save(user);
return "redirect:/users/list";
}
@GetMapping("/list")
public String listUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "userList";
}
}
4.2 使用Thymeleaf模板引擎
- 添加Thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 创建模板文件
src/main/resources/templates/register.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h1>User Registration</h1>
<form th:action="@{/users/register}" th:object="${user}" method="post">
<div>
<label for="name">Name:</label>
<input type="text" id="name" th:field="*{name}" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" th:field="*{email}" required>
</div>
<button type="submit">Register</button>
</form>
</body>
</html>
- 创建
userList.html
显示用户列表:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</tbody>
</table>
</body>
</html>
第五部分:Spring Boot高级特性
5.1 使用Actuator监控应用
- 添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 配置
application.properties
:
# 暴露所有端点
management.endpoints.web.exposure.include=*
# 显示健康详情
management.endpoint.health.show-details=always
访问以下端点获取应用信息:
/actuator/health
– 应用健康状态/actuator/info
– 应用信息/actuator/metrics
– 应用指标/actuator/env
– 环境变量
5.2 自定义配置属性
- 创建自定义配置类
AppProperties.java
:
package com.example.demo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String description;
private int maxUsers;
// getters and setters
}
- 在
application.properties
中添加配置:
app.name=My Spring Boot App
app.description=This is a demo application
app.max-users=100
- 在控制器中使用配置:
@RestController
public class ConfigController {
private final AppProperties appProperties;
public ConfigController(AppProperties appProperties) {
this.appProperties = appProperties;
}
@GetMapping("/config")
public AppProperties getConfig() {
return appProperties;
}
}
第六部分:测试与部署
6.1 编写单元测试
创建UserServiceTest.java
:
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@SpringBootTest
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void testCreateUser() {
User user = new User();
user.setName("Test User");
user.setEmail("test@example.com");
when(userRepository.save(any(User.class))).thenReturn(user);
User created = userService.createUser(user);
assertEquals("Test User", created.getName());
assertEquals("test@example.com", created.getEmail());
}
}
6.2 打包与部署
打包为可执行JAR:
mvn clean package
生成的JAR文件位于target/demo-0.0.1-SNAPSHOT.jar
运行应用:
java -jar target/demo-0.0.1-SNAPSHOT.jar
构建Docker镜像:
- 创建
Dockerfile
:
FROM eclipse-temurin:17-jdk-jammy
WORKDIR /app
COPY target/demo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
- 构建并运行:
docker build -t demo-app .
docker run -p 8080:8080 demo-app
第七部分:最佳实践与扩展学习
7.1 Spring Boot开发最佳实践
- 项目结构组织:
- 按功能而非层次组织代码(如
com.example.user
包含控制器、服务、仓库等) - 使用清晰的包命名(
controller
,service
,repository
,config
,model
等)
- 异常处理:
- 使用
@ControllerAdvice
全局处理异常 - 创建自定义异常类
- 返回统一的错误响应格式
- API设计:
- 遵循RESTful原则
- 使用DTO而非直接暴露实体
- 实现HATEOAS(超媒体驱动)
- 安全实践:
- 使用Spring Security
- 实施适当的认证和授权
- 保护敏感配置(使用Vault或环境变量)
7.2 推荐学习路径
- Spring官方文档:
- 进阶主题:
- Spring Security
- Spring Cloud(微服务)
- Spring Data Reactive(响应式编程)
- Spring Batch(批处理)
- Spring Integration(企业集成)
- 相关技术:
- Docker和Kubernetes
- 消息队列(RabbitMQ, Kafka)
- 监控(Prometheus, Grafana)
- 测试(Testcontainers, Mockito)
结语
通过本教程,您已经掌握了Spring Boot的基础知识和核心开发技能。从项目创建、Web开发、数据访问到测试部署,Spring Boot提供了一套完整的解决方案来简化Java应用开发。随着实践的深入,您会发现Spring Boot生态系统的强大和灵活。
记住,学习Spring Boot最好的方式就是动手实践。尝试基于本教程创建一个自己的项目,逐步添加更多功能,探索Spring Boot提供的各种特性。当遇到问题时,Spring活跃的社区和丰富的文档将成为您强大的后盾。
祝您在Spring Boot的学习和开发之旅中取得成功!