🌟博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。 📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解) 👉感兴趣的可以先收藏起来,希望帮助更多的人
Spring Boot 从零到精通的完整学习路线:2025 最新版知识图谱
一、Spring Boot 入门
1.1 Spring Boot 简介
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的配置方式,从而使开发人员不再需要定义样板化的配置。通过 Spring Boot,开发人员可以快速搭建一个独立运行、生产级别的基于 Spring 框架的应用程序。
1.2 开发环境搭建
1.2.1 JDK 安装
确保你的系统已经安装了 JDK 8 或更高版本。你可以从 Oracle 官方网站或者 OpenJDK 网站下载适合你操作系统的 JDK 安装包,然后按照安装向导进行安装。安装完成后,配置好 JAVA_HOME 环境变量。
1.2.2 Maven 或 Gradle 安装
Maven 和 Gradle 是 Java 项目中常用的构建工具,Spring Boot 项目可以使用它们来管理依赖和构建项目。你可以从 Maven 官方网站下载 Maven 安装包,解压后配置好 MAVEN_HOME 环境变量。Gradle 则可以通过官方网站下载或者使用 SDKMAN 进行安装。
1.2.3 IDE 安装
推荐使用 IntelliJ IDEA 或 Eclipse 作为开发工具。IntelliJ IDEA 是一款功能强大的 Java 集成开发环境,提供了丰富的插件和工具,能大大提高开发效率。
1.3 创建第一个 Spring Boot 项目
1.3.1 使用 Spring Initializr
Spring Initializr 是一个基于 Web 的工具,可用于快速生成 Spring Boot 项目的骨架。访问 Spring Initializr,在网页上选择项目的元数据,如项目类型(Maven 或 Gradle)、语言(Java)、Spring Boot 版本等,添加所需的依赖(如 Spring Web),然后点击 “Generate” 按钮下载项目压缩包。
1.3.2 导入项目到 IDE
将下载的项目压缩包解压后,使用 IntelliJ IDEA 或 Eclipse 导入项目。在 IntelliJ IDEA 中,选择 “File” -> “New” -> “Project from Existing Sources”,选择解压后的项目目录,按照向导完成项目导入。
1.3.3 编写 Hello World 示例
在项目的 src/main/java 目录下找到主应用类,通常以 Application 结尾。在该类中添加一个简单的控制器类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
@RestController
class HelloWorldController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
运行主应用类的 main 方法,启动 Spring Boot 应用。在浏览器中访问 http://localhost:8080/hello,如果看到 “Hello, World!” 则表示项目搭建成功。
二、Spring Boot 核心特性
2.1 自动配置
Spring Boot 的自动配置是其核心特性之一,它可以根据项目中添加的依赖自动配置 Spring 应用程序。例如,当你在项目中添加了 spring-boot-starter-web 依赖时,Spring Boot 会自动配置嵌入式的 Tomcat 服务器、Spring MVC 等。
2.1.1 自动配置原理
Spring Boot 的自动配置是基于 @EnableAutoConfiguration 注解实现的。该注解会触发 Spring Boot 的自动配置机制,它会根据类路径下的依赖和配置文件中的属性来自动配置 Spring 应用程序。
2.1.2 自定义自动配置
如果你需要自定义自动配置,可以创建一个配置类,并使用 @Configuration 和 @ConditionalOnClass 等注解来控制配置的生效条件。例如:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ConditionalOnClass;
@Configuration
@ConditionalOnClass(MyService.class)
public class MyAutoConfiguration {
@Bean
public MyService myService() {
return new MyService();
}
}
2.2 起步依赖
起步依赖是 Spring Boot 提供的一种简化依赖管理的方式,它是一组经过精心挑选的依赖集合,用于解决特定的开发场景。例如,spring-boot-starter-web 包含了 Spring MVC、嵌入式 Tomcat 等依赖,使用它可以快速搭建一个 Web 应用程序。
2.2.1 常用起步依赖介绍
spring-boot-starter-web:用于构建 Web 应用程序,包括 Spring MVC 和嵌入式 Tomcat 服务器。spring-boot-starter-data-jpa:用于使用 JPA 进行数据访问,包含了 Hibernate、Spring Data JPA 等依赖。spring-boot-starter-security:用于为应用程序添加安全认证和授权功能。
2.2.2 自定义起步依赖
如果你需要创建自定义的起步依赖,可以创建一个 Maven 或 Gradle 项目,在项目中定义所需的依赖,然后将其打包成一个独立的依赖包。
2.3 配置文件
Spring Boot 支持多种配置文件格式,如 application.properties 和 application.yml。配置文件可以用于配置应用程序的各种属性,如服务器端口、数据库连接信息等。
2.3.1 application.properties 配置
在 src/main/resources 目录下创建 application.properties 文件,添加以下配置:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
2.3.2 application.yml 配置
application.yml 是一种更易读的配置文件格式,与 application.properties 等效。在 src/main/resources 目录下创建 application.yml 文件,添加以下配置:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
2.3.3 多环境配置
Spring Boot 支持多环境配置,可以根据不同的环境(如开发、测试、生产)使用不同的配置文件。可以创建 application-dev.properties、application-test.properties 和 application-prod.properties 等文件,在启动应用程序时通过 spring.profiles.active 属性指定使用的环境。
三、Spring Boot 数据库访问
3.1 JDBC 访问
3.1.1 配置 JDBC 数据源
在 application.properties 或 application.yml 中配置 JDBC 数据源:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.1.2 使用 JdbcTemplate 进行数据库操作
JdbcTemplate 是 Spring 提供的一个简单而强大的 JDBC 操作工具类。以下是一个使用 JdbcTemplate 查询数据的示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public List
String sql = "SELECT * FROM users";
return jdbcTemplate.queryForList(sql);
}
}
3.2 JPA 访问
3.2.1 配置 JPA 数据源
在 application.properties 或 application.yml 中配置 JPA 数据源:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3.2.2 创建实体类和 Repository 接口
创建一个实体类 User:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// 省略 getter 和 setter 方法
}
创建一个 Repository 接口 UserRepository:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository
}
3.2.3 使用 Repository 接口进行数据库操作
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List
return userRepository.findAll();
}
}
3.3 MyBatis 访问
3.3.1 配置 MyBatis
在 pom.xml 中添加 MyBatis 和 MyBatis-Spring-Boot-Starter 依赖:
在 application.properties 或 application.yml 中配置 MyBatis:
mybatis.mapper-locations=classpath:mapper/*.xml
3.3.2 创建实体类和 Mapper 接口
创建一个实体类 User:
public class User {
private Long id;
private String name;
private Integer age;
// 省略 getter 和 setter 方法
}
创建一个 Mapper 接口 UserMapper:
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
List
}
3.3.3 创建 Mapper XML 文件
在 src/main/resources/mapper 目录下创建 UserMapper.xml 文件:
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
SELECT * FROM users
四、Spring Boot Web 开发
4.1 Spring MVC
4.1.1 控制器和请求映射
使用 @RestController 和 @GetMapping、@PostMapping 等注解来创建控制器和处理请求。例如:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring MVC!";
}
}
4.1.2 请求参数处理
可以使用 @RequestParam、@PathVariable 等注解来处理请求参数。例如:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ParamController {
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Long id) {
return "User ID: " + id;
}
@GetMapping("/search")
public String search(@RequestParam String keyword) {
return "Search keyword: " + keyword;
}
}
4.1.3 视图解析器
Spring MVC 支持多种视图解析器,如 JSP、Thymeleaf 等。以 Thymeleaf 为例,在 pom.xml 中添加 Thymeleaf 依赖:
创建一个 Thymeleaf 模板文件 hello.html:
Hello
创建一个控制器来返回视图:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String thymeleaf(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "hello";
}
}
4.2 RESTful API 开发
4.2.1 RESTful 架构风格
RESTful 是一种基于 HTTP 协议的架构风格,它使用 URL 和 HTTP 方法来表示资源和操作。例如,使用 GET 方法获取资源,使用 POST 方法创建资源,使用 PUT 方法更新资源,使用 DELETE 方法删除资源。
4.2.2 创建 RESTful API
创建一个 User 实体类和 UserController 控制器:
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private List
@GetMapping
public List
return users;
}
@PostMapping
public User createUser(@RequestBody User user) {
users.add(user);
return user;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return users.stream()
.filter(user -> user.getId().equals(id))
.findFirst()
.orElse(null);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId().equals(id)) {
users.set(i, updatedUser);
return updatedUser;
}
}
return null;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
users.removeIf(user -> user.getId().equals(id));
}
}
4.3 异常处理
4.3.1 全局异常处理器
使用 @ControllerAdvice 和 @ExceptionHandler 注解创建全局异常处理器。例如:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity
return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
五、Spring Boot 安全
5.1 Spring Security 简介
Spring Security 是一个强大且高度可定制的身份验证和访问控制框架,用于为 Spring 应用程序提供安全保障。它可以集成到 Spring Boot 项目中,提供基于表单的登录、基本认证、OAuth2 等多种认证方式。
5.2 基本认证配置
5.2.1 添加 Spring Security 依赖
在 pom.xml 中添加 Spring Security 依赖:
5.2.2 配置基本认证
创建一个配置类 SecurityConfig:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
}
5.3 基于表单的登录配置
5.3.1 配置基于表单的登录
修改 SecurityConfig 类以支持基于表单的登录:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
return http.build();
}
}
上述代码中,loginPage("/login") 指定了自定义的登录页面路径,permitAll() 表示该登录页面允许所有用户访问,同时配置了退出登录的相关设置并允许所有用户执行退出操作。
5.3.2 创建登录页面
在 src/main/resources/templates 目录下创建 login.html 文件:
Login
此登录页面包含用户名和密码输入框以及登录按钮,表单提交的地址为 /login。
5.3.3 创建登录控制器
创建一个控制器来处理登录页面的请求:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
}
当用户访问 /login 路径时,会返回 login.html 页面。
5.4 OAuth2 认证
5.4.1 引入 OAuth2 依赖
在 pom.xml 中添加 Spring Security OAuth2 相关依赖:
5.4.2 配置 OAuth2 客户端
在 application.properties 或 application.yml 中配置 OAuth2 客户端信息,以 GitHub 为例:
spring.security.oauth2.client.registration.github.client-id=your-client-id
spring.security.oauth2.client.registration.github.client-secret=your-client-secret
spring.security.oauth2.client.registration.github.scope=read:user
spring.security.oauth2.client.provider.github.authorization-uri=https://github.com/login/oauth/authorize
spring.security.oauth2.client.provider.github.token-uri=https://github.com/login/oauth/access_token
spring.security.oauth2.client.provider.github.user-info-uri=https://api.github.com/user
将 your-client-id 和 your-client-secret 替换为你在 GitHub 上创建的 OAuth 应用的实际信息。
5.4.3 配置 OAuth2 安全
修改 SecurityConfig 类以支持 OAuth2 登录:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
}
}
六、Spring Boot 测试
6.1 单元测试
6.1.1 引入测试依赖
在 pom.xml 中添加 Spring Boot Test 依赖:
6.1.2 编写单元测试
以测试一个简单的服务类为例:
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MyServiceTest {
@Test
public void testMyService() {
// 测试逻辑
}
}
6.2 集成测试
6.2.1 模拟 HTTP 请求
使用 MockMvc 来模拟 HTTP 请求进行集成测试:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(MyController.class)
public class MyControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testMyController() throws Exception {
mockMvc.perform(get("/test"))
.andExpect(status().isOk());
}
}
6.2.2 数据库集成测试
使用 @DataJpaTest 注解进行数据库集成测试:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@DataJpaTest
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void testUserRepository() {
User user = new User();
user.setName("Test User");
User savedUser = userRepository.save(user);
assertNotNull(savedUser.getId());
}
}
七、Spring Boot 部署与监控
7.1 部署方式
7.1.1 打包成可执行 JAR
使用 Maven 或 Gradle 命令将 Spring Boot 项目打包成可执行 JAR 文件:
mvn clean package
或者
gradle build
打包完成后,在 target 或 build/libs 目录下会生成一个可执行的 JAR 文件,通过以下命令运行:
java -jar your-application.jar
7.1.2 部署到容器
可以将 Spring Boot 应用部署到 Docker 容器中。首先创建一个 Dockerfile:
FROM openjdk:17-jdk-slim
COPY target/your-application.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
然后使用 Docker 命令构建和运行容器:
docker build -t your-application .
docker run -p 8080:8080 your-application
7.2 监控与管理
7.2.1 引入 Actuator
在 pom.xml 中添加 Spring Boot Actuator 依赖:
7.2.2 配置 Actuator
在 application.properties 或 application.yml 中配置 Actuator 端点:
management.endpoints.web.exposure.include=*
7.2.3 访问 Actuator 端点
启动应用程序后,可以通过访问 /actuator 路径查看所有可用的端点,例如 /actuator/health 用于查看应用程序的健康状态。
八、Spring Boot 高级特性
8.1 微服务与 Spring Cloud
8.1.1 Spring Cloud 简介
Spring Cloud 是一个用于构建分布式系统的工具集,它提供了服务发现、配置管理、断路器、路由等功能,帮助开发者更轻松地构建微服务架构。
8.1.2 服务发现与注册
使用 Spring Cloud Netflix Eureka 或 Spring Cloud Consul 实现服务发现与注册。以 Eureka 为例,在服务端添加依赖:
在配置类上添加 @EnableEurekaServer 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
在客户端添加依赖:
在配置文件中配置 Eureka 服务地址,并在主类上添加 @EnableEurekaClient 注解。
8.2 响应式编程
8.2.1 引入 Spring WebFlux
在 pom.xml 中添加 Spring WebFlux 依赖:
8.2.2 创建响应式控制器
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class ReactiveController {
@GetMapping("/reactive")
public Mono
return Mono.just("Hello, Reactive!");
}
}
8.3 消息队列集成
8.3.1 集成 RabbitMQ
在 pom.xml 中添加 Spring Boot Starter for RabbitMQ 依赖:
配置 RabbitMQ 连接信息:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
创建消息发送者和接收者:
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", message);
}
}
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
@Service
public class MessageReceiver {
@RabbitListener(queues = "myQueue")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}