01-spring-boot全栈Web开发

知识库
知识库文档
/tech-stacks/java/tutorial/01-spring-boot全栈Web开发.md

文档

Java 入门篇:Spring Boot 3 全栈 Web 开发

背景

Spring Boot 是 Java 生态中最流行的微服务框架,用"约定大于配置"的理念大幅简化了 Spring 应用的搭建。本教程带你构建一个完整的用户管理系统。

核心概念

1. 控制反转(IoC)和依赖注入(DI)

Spring 容器管理 Bean 的生命周期和依赖关系。用 @Autowired(或构造函数注入)声明依赖,Spring 自动装配。

// 推荐:构造函数注入
@RestController
public class UserController {
    private final UserService service;
    public UserController(UserService service) {
        this.service = service;  // Spring 自动注入
    }
}

2. Spring MVC 请求流程

Client → DispatcherServlet → HandlerMapping
       → Controller → Service → Repository → DB
       → 返回 → ViewResolver / HttpMessageConverter

3. 常用注解速查

注解 作用
@SpringBootApplication 组合了 @Configuration@EnableAutoConfiguration@ComponentScan
@RestController 组合了 @Controller + @ResponseBody,返回 JSON/文本
@GetMapping("/path") 映射 GET 请求
@PathVariable 提取 URL 路径参数
@RequestParam 提取查询参数
@RequestBody 提取 JSON 请求体
@Service 标记业务逻辑层组件
@Repository 标记数据访问层组件
@Transactional 声明式事务管理

分步操作

第一步:创建项目

# 用 Spring Initializr: https://start.spring.io
# 依赖选: Spring Web, Spring Data JPA, H2 Database, Lombok, Validation

第二步:三层架构

controller/   ← 接收请求,返回响应
service/      ← 业务逻辑
repository/   ← 数据访问(JPA)
entity/       ← 实体类
dto/          ← 数据传输对象

第三步:实现 Service 层

@Service
@Transactional
public class UserService {
    private final UserRepository repo;
    public UserService(UserRepository repo) { this.repo = repo; }

    public List<UserDTO> findAll() {
        return repo.findAll().stream()
            .map(UserDTO::fromEntity)
            .toList();
    }
}

第四步:异常处理

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<?> handleNotFound(EntityNotFoundException ex) {
        return ResponseEntity.status(404).body(Map.of("error", ex.getMessage()));
    }
}

第五步:集成 Swagger/OpenAPI

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.6.0</version>
</dependency>

访问 http://localhost:8080/swagger-ui.html 查看 API 文档。

思考题

  1. @Component@Service@Repository 有什么区别?能否互换?
  2. @Transactional 的传播行为(Propagation)有哪些?REQUIRED vs REQUIRES_NEW 的区别?
  3. Spring Boot 自动配置原理是什么?@ConditionalOnClass 如何工作?

信息

路径
/tech-stacks/java/tutorial/01-spring-boot全栈Web开发.md
更新时间
2026/5/30