如何使用Java Spring Boot构建REST API
        
        作者:API传播员 · 2025-09-12 · 阅读时间:7分钟
    
    
    
          
     
    
        
        本教程详细介绍了如何使用Java Spring Boot构建REST API,从项目初始化到创建RESTful端点、数据库集成和异常处理。通过Spring Initializr快速搭建项目结构,使用JPA实现数据持久化,并演示了控制器层与业务逻辑层的开发。最后涵盖Maven打包和云部署(AWS/Google Cloud)的完整流程,帮助开发者掌握企业级REST API开发的核心技术栈。
    
    
        
                
                文章目录
            
			
一. REST 与 Spring Boot 概述。
在现代 Web 开发中,REST(Representational State Transfer,代表性状态传输)是一种架构风格,它利用标准 HTTP 方法(如 GET、POST、PUT、DELETE)实现资源的创建、读取、更新和删除(CRUD)。RESTful API 是无状态的,允许客户端通过标准 HTTP 谓词与资源交互。
Spring Boot 是基于 Spring 框架的开源框架,旨在简化独立生产级应用的开发。它提供嵌入式服务器、安全性、监控等非功能特性,同时减少样板代码,使其成为构建 REST API 的理想选择。
二. 设置开发环境。
在开始构建 REST API 之前,需准备以下环境:
1. 安装 Java 开发工具包(JDK)
2. 集成开发环境(IDE)
- 推荐 IntelliJ IDEA(对 Spring Boot 支持友好)。
- 可选:Eclipse 或其他 Java IDE。
3. 构建工具
三. 创建 Spring Boot 项目。
使用 Spring Initializr 快速生成项目:
1. 生成 Spring Boot 项目
- 访问 Spring Initializr。
- 
配置: - 项目类型:Maven
- 语言:Java
- Spring Boot 版本:选择稳定版本
 
- 
添加依赖: - Spring Web:构建 Web 和 RESTful 应用
- Spring Data JPA:通过 JPA 与数据库交互
- H2 数据库:开发和测试时使用
 
- 点击 Generate 下载 .zip文件。
2. 导入项目到 IDE
- 解压 .zip文件。
- 在 IDE 中以 Maven 项目导入。
- IDE 自动下载依赖并设置项目结构。
四. 理解 Spring Boot 项目结构。
典型项目结构如下:
src/main/java/com/example/restapi/
├── RestApiApplication.java       // 主应用程序入口
├── model/                        // 实体类
├── repository/                   // 数据库交互接口
├── service/                      // 业务逻辑层
├── controller/                   // 控制器层
└── resources/application.properties // 配置文件五. 构建 REST API。
以管理 Product 实体为例:
1. 创建模型(Model)
package com.example.restapi.model;
import jakarta.persistence.*;
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    // Getters and Setters
}2. 创建存储库(Repository)
package com.example.restapi.repository;
import com.example.restapi.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository < Product, Long > {
}3. 创建服务层(Service)
package com.example.restapi.service;
import com.example.restapi.model.Product;
import com.example.restapi.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
    public List < Product > getAllProducts() {
        return productRepository.findAll();
    }
    public Optional < Product > getProductById(Long id) {
        return productRepository.findById(id);
    }
    public Product createProduct(Product product) {
        return productRepository.save(product);
    }
    public Product updateProduct(Long id, Product productDetails) {
        Product product = productRepository.findById(id)
                .orElseThrow(() - > new RuntimeException("Product not found"));
        product.setName(productDetails.getName());
        product.setPrice(productDetails.getPrice());
        return productRepository.save(product);
    }
    public void deleteProduct(Long id) {
        Product product = productRepository.findById(id)
                .orElseThrow(() - > new RuntimeException("Product not found"));
        productRepository.delete(product);
    }
}4. 创建控制器(Controller)
package com.example.restapi.controller;
import com.example.restapi.model.Product;
import com.example.restapi.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    @GetMapping
    public List < Product > getAllProducts() {
        return productService.getAllProducts();
    }
    @GetMapping("/{id}")
    public ResponseEntity < Product > getProductById(@PathVariable Long id) {
        Optional < Product > product = productService.getProductById(id);
        return product.map(ResponseEntity::ok)
                .orElseGet(() - > ResponseEntity.notFound().build());
    }
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }
    @PutMapping("/{id}")
    public ResponseEntity < Product > updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
        Product updatedProduct = productService.updateProduct(id, productDetails);
        return ResponseEntity.ok(updatedProduct);
    }
    @DeleteMapping("/{id}")
    public ResponseEntity < Void > deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}六. 处理 HTTP 方法。
Spring Boot 提供注解处理常用 HTTP 请求:
- @GetMapping:获取资源
- @PostMapping:创建资源
- @PutMapping:更新资源
- @DeleteMapping:删除资源
七. 错误处理。
通过全局异常处理器提供一致的错误响应:
package com.example.restapi.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity < String > handleRuntimeException(RuntimeException ex, WebRequest request) {
        return new ResponseEntity < > (ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}八. 部署 REST API。
1. 构建项目
mvn clean package2. 运行 JAR 文件
java -jar target/restapi-0.0.1-SNAPSHOT.jar3. 部署到云平台
- 可部署到 AWS 或 Google Cloud,利用云端自动化部署工具。
九. 总结。
通过本指南,您掌握了使用 Java Spring Boot 构建 REST API 的核心步骤:
- 项目初始化与依赖管理
- 模型、存储库、服务层及控制器创建
- HTTP 方法与错误处理
- 本地和云端部署
Spring Boot 提供了强大的生态系统和社区支持,使其成为构建企业级 RESTful 服务的理想选择。
原文链接
热门推荐
        一个账号试用1000+ API
            助力AI无缝链接物理世界 · 无需多次注册
            
        3000+提示词助力AI大模型
            和专业工程师共享工作效率翻倍的秘密
            
        热门API
- 1. AI文本生成
- 2. AI图片生成_文生图
- 3. AI图片生成_图生图
- 4. AI图像编辑
- 5. AI视频生成_文生视频
- 6. AI视频生成_图生视频
- 7. AI语音合成_文生语音
- 8. AI文本生成(中国)
最新文章
- Kimi K2 API 调用全指南:解锁国产大模型的强大能力
- Amazon的API描述语言Smithy概述
- 向日葵开放平台:如何让远程办公和支持变得轻而易举?
- 常见的api认证方式:应用场景与优势
- Deribit API – 入门指南
- AI推理(Reasoning AI)技术趋势2025:从大模型到智能体的全面升级
- Dify 全链路实战:三步搭建智能天气查询机器人(Agent+DeepSeek + 高德天气)
- 2025年GitHub开源生成式 AI API 项目盘点:Open WebUI、FastAPI LLM Server、Text Generation WebUI API
- WebSocket和REST的区别:功能、适用范围、性能与示例解析
- 如何使用API密钥实现API认证 | 作者:Jaz Allibhai
- 9个最佳Text2Sql开源项目:自然语言到SQL的高效转换工具
- 深入解析API网关策略:认证、授权、安全、流量处理与可观测性