从 0 到 1 实战 Spring Boot 3:手把手教你构建高效 RESTful 接口
ztj100 2025-05-08 08:10 39 浏览 0 评论
从 0 到 1 实战 Spring Boot 3:手把手教你构建高效 RESTful 接口
在微服务架构盛行的今天,构建高效稳定的 RESTful 接口是后端开发者的核心技能。Spring Boot 凭借其 “开箱即用” 的特性,成为快速构建 RESTful 服务的首选框架。本文将以 Spring Boot 3 为基础,通过实战案例带你从环境搭建到接口落地,掌握企业级 RESTful 接口开发的全流程。
一、搭建 Spring Boot 3 项目
首先访问Spring Initializr,配置以下参数:
- 项目类型:Maven Project
- 语言:Java
- Spring Boot 版本:3.2.0(当前最新稳定版)
- 依赖:Spring Web、Spring Data JPA、H2 Database
生成项目后导入 IDE,项目结构如下:
plaintext
src
├── main
│ ├── java
│ │ └── com.example.demo
│ │ ├── DemoApplication.java
│ │ ├── controller
│ │ ├── entity
│ │ └── repository
│ └── resources
│ └── application.properties
在application.properties中添加 H2 数据库配置:
properties
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=update
二、创建数据实体与 Repository
以用户管理为例,创建User实体类:
java
package com.example.demo.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
private Integer age;
// 省略getter和setter
}
创建UserRepository接口继承JpaRepository:
java
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
三、编写 RESTful 接口控制器
创建UserController,实现 CRUD 操作:
java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
// 获取所有用户
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userRepository.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
// 根据ID获取用户
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
return userRepository.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
// 创建新用户
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userRepository.save(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
// 更新用户
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
return userRepository.findById(id)
.map(existingUser -> {
existingUser.setUsername(user.getUsername());
existingUser.setEmail(user.getEmail());
existingUser.setAge(user.getAge());
User updatedUser = userRepository.save(existingUser);
return ResponseEntity.ok(updatedUser);
})
.orElse(ResponseEntity.notFound().build());
}
// 删除用户
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
return userRepository.findById(id)
.map(existingUser -> {
userRepository.delete(existingUser);
return ResponseEntity.noContent().build();
})
.orElse(ResponseEntity.notFound().build());
}
}
四、接口测试与优化
- 启动 H2 控制台:访问http://localhost:8080/h2-console,使用默认配置登录,手动插入测试数据。
- 使用 Postman 测试:GET /api/users 获取所有用户POST /api/users 提交 JSON 数据创建用户PUT /api/users/1 更新指定用户DELETE /api/users/1 删除用户
- 异常处理增强:添加全局异常处理类:
java
package com.example.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("Internal server error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
五、总结与扩展
通过本文的实战演练,你已经掌握了 Spring Boot 3 构建 RESTful 接口的核心流程。实际开发中可以进一步扩展:
- 添加请求参数校验(使用@Valid和BindingResult)
- 集成 Swagger 生成接口文档
- 实现分页查询(使用Pageable)
- 添加缓存机制(使用 Spring Cache)
Spring Boot 3 的简化配置和强大生态,让开发者能够更专注于业务逻辑实现。立即动手实践,将这些技能应用到你的下一个项目中吧!
相关推荐
- 能量空间物质相互转化途径(能量与空间转换相对论公式)
-
代码实现<!DOCTYPEhtml><htmllang="zh"><head>...
- 从零开始的Flex布局掌握(flex布局实战)
-
前言在现代网页设计中,布局是一个至关重要的环节,在过去的一段时间里,页面的布局还都是通过table...
- flex布局在css中的使用,一看就会!
-
1.认识flex布局我们在写前端页面的时候可能会遇到这样的问题:同样的一个页面在1920x1080的大屏幕中显示正常,但是在1366x768的小屏幕中却显示的非常凌乱。...
- 前端入门——弹性布局(Flex)(web前端弹性布局)
-
前言在css3Flex技术出现之前制作网页大多使用浮动(float)、定位(position)以及显示(display)来布局页面,随着互联网快速发展,移动互联网的到来,已无法满足需求,它对于那些...
- CSS Flex 容器完整指南(css flex-shrink)
-
概述CSSFlexbox是现代网页布局的强大工具。本文详细介绍用于flex容器的CSS属性:...
- Centos 7 network.service 启动失败
-
执行systemctlrestartnetwork重启网络报如下错误:Jobfornetwork.servicefailedbecausethecontrolprocessex...
- CentOS7 执行systemctl start iptables 报错:...: Unit not found.
-
#CentOS7执行systemctlstartiptables报错:Failedtostartiptables.service:Unitnotfound.在CentOS7中...
- systemd入门6:journalctl的详细介绍
-
该来的总会来的,逃是逃不掉的。话不多说,man起来:manjournalctl洋洋洒洒几百字的描述,是说journalctl是用来查询systemd日志的,这些日志都是systemd-journa...
- Linux上的Systemctl命令(systemctl命令详解)
-
LinuxSystemctl是一个系统管理守护进程、工具和库的集合,用于取代SystemV、service和chkconfig命令,初始进程主要负责控制systemd系统和服务管理器。通过Syste...
- 如何使用 systemctl 管理服务(systemctl添加服务)
-
systemd是一个服务管理器,目前已经成为Linux发行版的新标准。它使管理服务器变得更加容易。了解并利用组成systemd的工具将有助于我们更好地理解它提供的便利性。systemctl的由来...
- 内蒙古2024一分一段表(文理)(内蒙古考生2020一分一段表)
-
分数位次省份...
- 2016四川高考本科分数段人数统计,看看你有多少竞争对手
-
昨天,四川高考成绩出炉,全省共220,196人上线本科,相信每个考生都查到了自己的成绩。而我们都清楚多考1分就能多赶超数百人,那你是否知道,和你的分数一样的人全省有几个人?你知道挡在你前面的有多少人?...
- 难怪最近电脑卡爆了,微软确认Win11资源管理器严重BUG
-
近期,Win11操作系统的用户普遍遭遇到了一个令人头大的问题:电脑卡顿,CPU占用率异常增高。而出现该现象的原因竟然与微软最近的一次补丁更新有关。据报道,微软已经确认,问题源于Win11资源管...
- 微软推送Win11正式版22621.1702(KB5026372)更新
-
IT之家5月10日消息,微软今天推送了最新的Win11系统更新,21H2正式版通道推送了KB5026368补丁,版本号升至22000.1936,22H2版本推送了KB50263...
- 骗子AI换脸冒充亲戚,女子转账10万元后才发现异常……
-
“今天全靠你们,不然我这被骗的10万元肯定就石沉大海了。”7月19日,家住石马河的唐女士遭遇了“AI”换脸诈骗,幸好她报警及时,民警对其转账给骗子的钱成功进行止付。当天13时许,唐女士收到一条自称是亲...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 能量空间物质相互转化途径(能量与空间转换相对论公式)
- 从零开始的Flex布局掌握(flex布局实战)
- flex布局在css中的使用,一看就会!
- 前端入门——弹性布局(Flex)(web前端弹性布局)
- CSS Flex 容器完整指南(css flex-shrink)
- Centos 7 network.service 启动失败
- CentOS7 执行systemctl start iptables 报错:...: Unit not found.
- systemd入门6:journalctl的详细介绍
- Linux上的Systemctl命令(systemctl命令详解)
- 如何使用 systemctl 管理服务(systemctl添加服务)
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)