Spring Boot 3 简介
什么是Spring Boot?
Spring Boot是一个用于简化Spring应用开发的框架,它提供了一套快速开发方案,遵循"约定优于配置"的原则,让开发者能够快速搭建并运行Spring应用程序。
核心特性
1. 自动配置 (Auto-Configuration)
根据classpath中的依赖自动配置Spring应用。
2. 起步依赖 (Starter Dependencies)
预定义的依赖集合,简化Maven配置。
3. 内嵌服务器
内置Tomcat、Jetty或Undertow,无需部署WAR文件。
4. 生产就绪特性
提供监控、健康检查、指标收集等功能。
5. 无代码生成和XML配置
完全基于Java配置和注解。
Spring Boot 3 新特性
Spring Boot 3.0是一个重大版本更新,主要特性包括:
基线要求
- Java 17+:最低要求Java 17
- Spring Framework 6:基于Spring 6构建
- Jakarta EE 9+:从javax.迁移到jakarta.
核心改进
- 原生镜像支持:通过GraalVM构建原生应用
- 可观测性增强:改进的Micrometer和Micrometer Tracing集成
- 问题详情支持:RFC 7807问题详情标准支持
- 性能优化:启动时间和内存占用优化
快速开始
1. 创建项目
使用Spring Initializr:
- 访问 https://start.spring.io/
- 选择Spring Boot 3.x
- 选择Java 17+
- 添加所需依赖
或使用Maven命令:
bash
mvn archetype:generate -DgroupId=com.example -DartifactId=demo \\
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false2. 项目结构
demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/demo/
│ │ │ ├── DemoApplication.java
│ │ │ ├── controller/
│ │ │ ├── service/
│ │ │ ├── repository/
│ │ │ └── domain/
│ │ └── resources/
│ │ ├── application.yml
│ │ ├── static/
│ │ └── templates/
│ └── test/
│ └── java/
├── pom.xml
└── README.md3. pom.xml配置
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>4. 主启动类
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);
}
}5. 配置文件
application.yml:
yaml
spring:
application:
name: demo
datasource:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
dialect: org.hibernate.dialect.MySQLDialect
server:
port: 8080
servlet:
context-path: /api
logging:
level:
root: INFO
com.example: DEBUG6. 创建第一个Controller
java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping
public String hello() {
return "Hello, Spring Boot 3!";
}
}7. 运行应用
bash
mvn spring-boot:run访问(示例运行地址,启动应用后访问):http://localhost:8080/api/hello
常用Starter依赖
Web开发
xml
<!-- Web应用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- WebFlux响应式Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- Thymeleaf模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>数据访问
xml
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- MongoDB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>安全
xml
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- OAuth2 Client -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>消息队列
xml
<!-- RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- Kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>监控和管理
xml
<!-- Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Prometheus -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>自动配置原理
@SpringBootApplication注解
java
@SpringBootApplication
// 等价于以下三个注解的组合:
@SpringBootConfiguration // 标记为配置类
@EnableAutoConfiguration // 启用自动配置
@ComponentScan // 组件扫描
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}条件注解
Spring Boot使用条件注解来决定是否应用某个配置:
java
@Configuration
@ConditionalOnClass(DataSource.class) // 当类存在时
@ConditionalOnMissingBean(DataSource.class) // 当Bean不存在时
@ConditionalOnProperty(name = "spring.datasource.url") // 当属性存在时
public class DataSourceAutoConfiguration {
@Bean
public DataSource dataSource() {
// 创建数据源
}
}常用条件注解:
@ConditionalOnClass:类存在时@ConditionalOnMissingClass:类不存在时@ConditionalOnBean:Bean存在时@ConditionalOnMissingBean:Bean不存在时@ConditionalOnProperty:配置属性存在时@ConditionalOnWebApplication:Web应用时@ConditionalOnNotWebApplication:非Web应用时
自定义自动配置
- 创建配置类:
java
@Configuration
@ConditionalOnClass(SomeService.class)
@EnableConfigurationProperties(SomeProperties.class)
public class SomeAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SomeService someService(SomeProperties properties) {
return new SomeService(properties);
}
}- 创建配置属性类:
java
@ConfigurationProperties(prefix = "some")
@Data
public class SomeProperties {
private boolean enabled = true;
private String apiKey;
private int timeout = 3000;
}- 注册自动配置:
在META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中:
com.example.autoconfigure.SomeAutoConfiguration配置文件
application.yml vs application.properties
properties
# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=rootyaml
# application.yml (推荐)
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: root多环境配置
application.yml # 公共配置
application-dev.yml # 开发环境
application-test.yml # 测试环境
application-prod.yml # 生产环境application.yml:
yaml
spring:
profiles:
active: dev # 激活dev环境application-dev.yml:
yaml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_dbapplication-prod.yml:
yaml
server:
port: 80
spring:
datasource:
url: jdbc:mysql://prod-server:3306/prod_db配置绑定
java
@ConfigurationProperties(prefix = "app")
@Component
@Data
public class AppProperties {
private String name;
private String version;
private Server server;
@Data
public static class Server {
private String host;
private int port;
}
}yaml
app:
name: MyApp
version: 1.0.0
server:
host: localhost
port: 8080使用:
java
@Service
public class SomeService {
@Autowired
private AppProperties appProperties;
public void doSomething() {
String name = appProperties.getName();
int port = appProperties.getServer().getPort();
}
}日志配置
默认日志框架
Spring Boot使用Logback作为默认日志框架。
配置日志级别
yaml
logging:
level:
root: INFO
com.example: DEBUG
org.springframework: WARN
org.hibernate: ERROR配置日志文件
yaml
logging:
file:
name: logs/app.log
max-size: 10MB
max-history: 30
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"使用日志
java
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class UserService {
public void createUser(User user) {
log.debug("Creating user: {}", user);
// ...
log.info("User created successfully: {}", user.getId());
}
}