Spring Boot 基础
是什么
Spring Boot 是基于 Spring Framework 的快速开发框架,核心目标是开箱即用:
- 自动配置:根据 classpath 依赖自动配置 Spring 组件,无需大量 XML
- 起步依赖(Starter):一个依赖包含所需的全部传递依赖
- 内嵌服务器:打包为可执行 jar,内嵌 Tomcat/Jetty/Undertow,无需外部容器
- 生产就绪:内置 Actuator 提供健康检查、指标采集等
版本关系
| Spring Boot | Spring Framework | Java 最低版本 |
|---|---|---|
| 3.x | 6.x | 17 |
| 2.7.x | 5.3.x | 8 |
| 2.x | 5.x | 8 |
Spring Boot 3.x 基于 Jakarta EE 9+,包名从 javax.* 改为 jakarta.*。
项目结构
src/
├── main/
│ ├── java/com/example/demo/
│ │ ├── DemoApplication.java # 启动类
│ │ ├── controller/ # 控制器
│ │ ├── service/ # 业务逻辑
│ │ ├── repository/ # 数据访问
│ │ ├── entity/ # 实体类
│ │ ├── dto/ # 数据传输对象
│ │ └── config/ # 配置类
│ └── resources/
│ ├── application.yml # 主配置
│ ├── application-dev.yml # 开发环境配置
│ ├── application-prod.yml # 生产环境配置
│ └── static/ # 静态资源
└── test/
└── java/com/example/demo/ # 测试代码
启动类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}@SpringBootApplication 是三个注解的组合,详见 启动流程:
| 注解 | 作用 |
|---|---|
@SpringBootConfiguration | 标记为配置类(@Configuration 的变体) |
@EnableAutoConfiguration | 开启自动配置 |
@ComponentScan | 扫描当前包及子包下的组件,详见 IOC 与 DI |
常用 Starter
| Starter | 作用 |
|---|---|
spring-boot-starter-web | Web MVC + 内嵌 Tomcat |
spring-boot-starter-webflux | 响应式 Web + 内嵌 Netty |
spring-boot-starter-data-jpa | JPA + Hibernate |
spring-boot-starter-data-redis | Redis 客户端 |
spring-boot-starter-data-mongodb | MongoDB |
spring-boot-starter-security | Spring Security |
spring-boot-starter-validation | 参数校验(Jakarta Validation) |
spring-boot-starter-cache | 缓存抽象 |
spring-boot-starter-aop | AOP |
spring-boot-starter-test | 测试(JUnit 5 + Mockito) |
spring-boot-starter-actuator | 监控端点 |
mybatis-spring-boot-starter | MyBatis 集成 |
配置文件
支持 .properties 和 .yml(推荐 YAML),详见 配置管理 与 环境与 Profile。
# application.yml
spring:
application:
name: demo-service
profiles:
active: dev # 激活的 profile
server:
port: 8080
servlet:
context-path: /api
# 自定义配置
app:
max-retry: 3
timeout: 5000多环境配置命名规则:application-{profile}.yml,激活方式:
# application.yml
spring:
profiles:
active: dev# 启动时指定
java -jar app.jar --spring.profiles.active=prod核心注解速查
Bean 注册
详见 IOC 与 DI、Bean 生命周期、Bean 作用域。
| 注解 | 说明 |
|---|---|
@Component | 通用组件 |
@Service | 业务层(语义化的 @Component) |
@Repository | 数据访问层,额外处理持久化异常 |
@Controller | MVC 控制器 |
@RestController | @Controller + @ResponseBody |
@Configuration | 配置类 |
@Bean | 在 @Configuration 类中声明 Bean |
依赖注入
// 推荐:构造器注入(final 字段,便于测试)
@Service
public class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) {
this.repo = repo;
}
}
// 字段注入(简洁但不推荐,难以测试)
@Autowired
private UserRepository repo;
// @Resource:按名称注入(JDK 注解)
@Resource(name = "userRepository")
private UserRepository repo;Web
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) { ... }
@GetMapping
public List<User> list(@RequestParam(defaultValue = "1") int page) { ... }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User create(@RequestBody @Valid CreateUserRequest req) { ... }
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody UpdateUserRequest req) { ... }
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) { ... }
}配置读取
详见 属性绑定。
// 读取单个值
@Value("${app.timeout:5000}") // 冒号后为默认值
private int timeout;
// 读取配置块(推荐)
@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
private int maxRetry;
private int timeout;
// getter / setter
}其他常用注解
| 注解 | 关联 |
|---|---|
@Transactional | 事务管理 |
@Cacheable / @CacheEvict | 缓存 |
@Scheduled | 定时任务 |
@Async | 异步与线程池 |
@PreAuthorize | 方法级安全 |
@Aspect / @Around | AOP |
@Valid / @Validated | 参数校验 |
@CrossOrigin | 跨域处理 |
内嵌服务器
默认内嵌 Tomcat,可切换为 Jetty 或 Undertow,详见 连接池配置 与 优雅停机。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>打包运行
# 打包为可执行 jar(包含依赖和内嵌服务器)
mvn clean package -DskipTests
# 运行
java -jar target/demo-0.0.1-SNAPSHOT.jar
# 指定配置
java -jar app.jar \
--spring.profiles.active=prod \
--server.port=9090 \
--spring.datasource.url=jdbc:mysql://db:3306/demopom.xml 需引入打包插件:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>常用配置项速查
server:
port: 8080
tomcat:
threads:
max: 200
min-spare: 10
connection-timeout: 20000
spring:
datasource: # 详见:连接池配置
url: jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 10
minimum-idle: 5
connection-timeout: 30000
jpa: # 详见:JPA 与 Hibernate
hibernate:
ddl-auto: validate
show-sql: false
open-in-view: false
data:
redis: # 详见:Redis 集成
host: localhost
port: 6379
password:
lettuce:
pool:
max-active: 8
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
default-property-inclusion: non_null
logging: # 详见:日志
level:
root: INFO
com.example: DEBUG
file:
name: logs/app.log