1. Spring Boot 快速启动

1 阅读5分钟

一、Spring Boot 简介

1. 什么是 Spring Boot?

Spring Boot:基于 Spring 框架的快速开发框架,通过约定优于配置、自动配置等特性,简化 Spring 应用的开发和部署。


2. Spring Boot 的核心价值

传统 SpringSpring Boot优势
需要大量 XML 配置自动配置减少配置
手动创建 Bean约定优于配置快速启动
部署复杂内嵌服务器简化部署
学习曲线陡峭开箱即用降低门槛
依赖管理复杂Starter 依赖简化依赖

3. Spring Boot 的特性

特性说明
自动配置根据依赖自动装配 Bean
Starter 依赖简化依赖管理
内嵌服务器无需部署外部服务器
生产级特性监控、健康检查、指标
无代码生成无需生成代理代码

二、快速创建项目

1. 使用 Spring Initializr

访问: start.spring.io/

步骤:

  1. 选择项目类型(Maven/Gradle)
  2. 选择 Spring Boot 版本
  3. 填写项目信息(Group、Artifact)
  4. 添加依赖(Web、JPA、MySQL)
  5. 生成项目并下载

2. 命令行创建(Spring Boot CLI)

# 安装 Spring Boot CLI(可选)
curl -s "https://get.sdkman.io" | bash
sdk install springboot

# 创建项目
spring init --dependencies=web,data-jpa,mysql my-app
cd my-app

3. IDEA 创建项目

步骤:

  1. File → New → Project
  2. 选择 Spring Initializr
  3. 填写项目信息
  4. 选择依赖
  5. 创建项目

三、项目结构

1. 标准项目结构

my-app/
├── pom.xml                          # Maven 配置文件
└── src/
    ├── main/
    │   ├── java/com/example/myapp/
    │   │   ├── MyApplication.java   # 启动类
    │   │   ├── controller/          # 控制器层
    │   │   ├── service/             # 服务层
    │   │   ├── repository/          # 仓库层
    │   │   ├── model/               # 实体类
    │   │   ├── dto/                 # 数据传输对象
    │   │   ├── config/              # 配置类
    │   │   └── exception/           # 异常处理
    │   └── resources/
    │       ├── application.properties  # 配置文件
    │       ├── static/              # 静态资源
    │       └── templates/           # 模板文件
    └── test/                       # 测试代码

2. 启动类(MyApplication.java)

package com.example.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication  // 启用自动配置、组件扫描
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);  // 启动应用
    }
}

@SpringBootApplication 注解解析:

@SpringBootConfiguration  // 标记为配置类
@EnableAutoConfiguration  // 启用自动配置(核心)
@ComponentScan            // 扫描组件(@Component、@Service、@Repository)
public @interface SpringBootApplication {
    // ...
}

四、第一个 Spring Boot 应用

1. 创建 Hello World Controller

HelloController.java:

package com.example.myapp.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController  // REST 控制器
public class HelloController {
    
    @GetMapping("/hello")  // GET /hello
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

2. 启动应用

方式 1:IDEA 运行

  • 右键点击 MyApplication.java
  • 选择 Run 'MyApplication'

方式 2:Maven 命令

mvn spring-boot:run

方式 3:打包运行

mvn clean package
java -jar target/my-app-1.0.0.jar

3. 访问应用

打开浏览器访问:

http://localhost:8080/hello

响应:

Hello, Spring Boot!

五、配置文件

1. 配置文件格式

Spring Boot 支持两种配置文件格式:

格式文件名说明
Propertiesapplication.properties传统格式
YAMLapplication.yml层级格式

2. application.properties 示例

# 服务器配置
server.port=8080
server.servlet.context-path=/api

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# 日志配置
logging.level.org.springframework.web=INFO
logging.level.com.example.myapp=DEBUG

3. application.yml 示例

server:
  port: 8080
  servlet:
    context-path: /api

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

logging:
  level:
    org.springframework.web: INFO
    com.example.myapp: DEBUG

4. 读取配置值

方式 1:@Value 注解

@Component
public class AppConfig {
    
    @Value("${app.name}")
    private String appName;
    
    @Value("${server.port}")
    private int serverPort;
}

方式 2:@ConfigurationProperties

AppProperties.java:

@Component
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
    private String name;
    private String version;
    private String description;
}

application.yml:

app:
  name: My Application
  version: 1.0.0
  description: Spring Boot Demo

使用:

@Service
public class MyService {
    
    @Autowired
    private AppProperties appProperties;
    
    public void printAppInfo() {
        System.out.println("App Name: " + appProperties.getName());
        System.out.println("Version: " + appProperties.getVersion());
    }
}

六、依赖管理

1. Starter 依赖

什么是 Starter?

Starter 是 Spring Boot 提供的一组便捷依赖描述符,整合了相关依赖。


2. 常用 Starter 依赖

Starter说明包含依赖
spring-boot-starter-webWeb 应用开发Spring MVC、Tomcat
spring-boot-starter-data-jpaJPA 数据持久化Hibernate、Spring Data JPA
spring-boot-starter-validation数据验证Hibernate Validator
spring-boot-starter-security安全认证Spring Security
spring-boot-starter-cache缓存支持Spring Cache
spring-boot-starter-test测试支持JUnit、Mockito

3. pom.xml 示例

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.0</version>
</parent>

<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>
    
    <!-- Validation -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </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>

七、内嵌服务器

1. 默认服务器

Spring Boot 默认使用 Tomcat 作为内嵌服务器。


2. 切换服务器

切换到 Jetty

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <!-- 排除 Tomcat -->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 添加 Jetty -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

切换到 Undertow

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <!-- 排除 Tomcat -->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 添加 Undertow -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

3. 服务器配置

application.properties:

# 服务器端口
server.port=8080

# 服务器地址
server.address=0.0.0.0

# 上下文路径
server.servlet.context-path=/api

# 最大线程数
server.tomcat.threads.max=200

# 最小线程数
server.tomcat.threads.min-spare=10

八、Actuator 监控

1. 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2. 配置 Actuator

application.properties:

# 启用所有端点
management.endpoints.web.exposure.include=*

# 启用健康检查
management.endpoint.health.show-details=always

# 基础路径
management.endpoints.web.base-path=/actuator

3. 常用端点

端点URL说明
健康检查/actuator/health应用健康状态
信息/actuator/info应用信息
指标/actuator/metrics应用指标
环境/actuator/env环境变量
日志/actuator/loggers日志配置

4. 访问健康检查

curl http://localhost:8080/actuator/health

响应:

{
  "status": "UP",
  "components": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 107374182400,
        "free": 53687091200,
        "threshold": 10485760,
        "exists": true
      }
    },
    "ping": {
      "status": "UP"
    }
  }
}

九、生产级特性

1. 健康检查

自定义健康检查:

@Component
public class DatabaseHealthIndicator implements HealthIndicator {
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public Health health() {
        try {
            long count = userRepository.count();
            return Health.up()
                    .withDetail("userCount", count)
                    .build();
        } catch (Exception e) {
            return Health.down()
                    .withDetail("error", e.getMessage())
                    .build();
        }
    }
}

2. 指标

自定义指标:

@Component
public class CustomMetrics {
    
    private final MeterRegistry registry;
    
    public CustomMetrics(MeterRegistry registry) {
        this.registry = registry;
    }
    
    public void recordUserRegistration() {
        Counter.builder("user.registration.count")
                .description("Number of user registrations")
                .register(registry)
                .increment();
    }
}

3. 日志配置

application.yml:

logging:
  level:
    root: INFO
    com.example.myapp: DEBUG
  
  file:
    name: logs/myapp.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"

十、最佳实践

1. 包名规范

规范示例
公司域名倒置com.example.myapp
小写字母controllerservice
复数名词usersproducts

2. 命名规范

类型规范示例
类名大驼峰UserController
方法名小驼峰findById
常量全大写下划线MAX_SIZE
包名小写controller

3. 分层架构

职责
Controller接收请求,返回响应
Service业务逻辑处理
Repository数据访问
Model实体映射
DTO数据传输