什么是 Spring Boot?
Spring Boot 是基于 Spring 框架的快速开发脚手架,它通过自动配置、起步依赖和内嵌服务器,极大地简化了 Spring 应用的搭建和开发过程。
环境准备
- JDK:Spring Boot 2.x 需要 JDK 8 及以上版本(推荐 JDK 11)
- Maven:3.3+ 版本
- IDE:IntelliJ IDEA / Eclipse / VS Code
快速开始
1. 创建项目
使用 Spring Initializr(https://start.spring.io)快速生成项目骨架。选择以下依赖:
- Spring Web:构建 Web 应用和 RESTful API
- Spring Boot DevTools:热部署,提升开发效率
- Lombok:减少样板代码
2. Maven 配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3. 编写第一个 Controller
@RestController
@RequestMapping("/api/v1")
public class HelloController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello, Spring Boot 2!");
}
}
4. 启动应用
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
运行 main 方法,访问 http://localhost:8080/api/v1/hello 即可看到返回结果。
核心概念
自动配置(Auto-Configuration)
Spring Boot 会根据类路径中的依赖自动配置 Spring 应用。例如,如果 classpath 中存在 spring-boot-starter-web,它就会自动配置 DispatcherServlet、嵌入式 Tomcat 等。
起步依赖(Starter Dependencies)
起步依赖是一组预定义的依赖集合,帮助你快速引入特定功能所需的所有 jar 包。常用 starter 包括:
spring-boot-starter-web:Web 开发spring-boot-starter-data-jpa:JPA + Hibernatespring-boot-starter-security:安全认证spring-boot-starter-test:测试框架
配置管理
Spring Boot 2 使用 application.yml 或 application.properties 进行配置:
# application.yml
server:
port: 8080
servlet:
context-path: /app
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
RESTful API 设计最佳实践
- 使用正确的 HTTP 方法:GET 查询、POST 创建、PUT 更新、DELETE 删除
- 统一返回格式:封装统一的响应体(code、message、data)
- 参数校验:使用
@Valid+@NotNull、@Size等注解 - 全局异常处理:使用
@ControllerAdvice+@ExceptionHandler
结语
Spring Boot 2 大大降低了 Spring 生态的入门门槛,让开发者可以专注于业务逻辑而非繁琐的配置。但随着 Spring Boot 3 的发布,官方已不再维护 2.x 版本,建议新项目直接使用 Spring Boot 3。