Spring Boot 入门指南:从零开始构建微服务

1. Spring Boot 简介

Spring Boot 是 Spring 框架的一个子项目,旨在简化 Spring 应用的初始搭建和开发过程。它通过自动配置、起步依赖和嵌入式服务器等特性,让开发者能够快速创建独立运行、生产级别的 Spring 应用程序。

2. 核心特性

  • 自动配置:根据项目依赖自动配置 Spring 应用。
  • 起步依赖:提供预配置的依赖包,简化 Maven/Gradle 配置。
  • 嵌入式服务器:内置 Tomcat、Jetty 或 Undertow,无需部署 WAR 包。
  • 生产就绪:提供健康检查、指标、外部化配置等生产级功能。
  • 无代码生成:无需 XML 配置,通过注解和约定实现配置。

3. 快速开始

使用 Spring Initializr 快速创建项目:

  1. 选择项目类型(Maven/Gradle)、语言(Java/Kotlin/Groovy)
  2. 选择 Spring Boot 版本(建议使用最新稳定版)
  3. 添加依赖(如 Web、JPA、Security 等)
  4. 点击生成并下载项目

4. 第一个 Spring Boot 应用

创建一个简单的 REST API:

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 DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Spring Boot!"; } }

5. 配置文件

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

  • application.properties:键值对格式
  • application.yml:YAML 格式,支持层级结构

示例application.yml

server: port: 8081 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: 123456 jpa: hibernate: ddl-auto: update show-sql: true

6. 常用注解

  • @SpringBootApplication:主启动类注解
  • @RestController:声明 RESTful 控制器
  • @RequestMapping/@GetMapping/@PostMapping:请求映射
  • @Autowired:自动注入依赖
  • @Component/@Service/@Repository:声明 Bean
  • @Configuration/@Bean:配置类与 Bean 定义

7. 数据库集成

Spring Boot 简化了数据库操作:

// 实体类 @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // getters and setters } // Repository 接口 public interface UserRepository extends JpaRepository<User, Long> { List<User> findByName(String name); } // Service 层 @Service public class UserService { @Autowired private UserRepository userRepository; public List&lt;User&gt; getAllUsers() { return userRepository.findAll(); } }

8. 测试

Spring Boot 提供了强大的测试支持:

import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; 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; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @SpringBootTest @AutoConfigureMockMvc class DemoApplicationTests { @Autowired private MockMvc mockMvc; @Test void helloEndpoint() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello, Spring Boot!")); } }

9. 部署与打包

Spring Boot 应用可以打包为可执行 JAR:

# 使用 Maven 打包 mvn clean package 运行 JAR 文件 java -jar target/demo-0.0.1-SNAPSHOT.jar 使用 Gradle 打包 gradle bootJar java -jar build/libs/demo-0.0.1-SNAPSHOT.jar

10. 学习资源

  • 官方文档:Spring Boot 官网
  • Spring Initializr:start.spring.io
  • GitHub 示例:Spring Boot GitHub
  • Spring Guides:官方教程指南