
如何利用API找回被盗的自行车
在现代 Web 开发中,REST(Representational State Transfer,代表性状态传输)是一种架构风格,它利用标准 HTTP 方法(如 GET、POST、PUT、DELETE)实现资源的创建、读取、更新和删除(CRUD)。RESTful API 是无状态的,允许客户端通过标准 HTTP 谓词与资源交互。
Spring Boot 是基于 Spring 框架的开源框架,旨在简化独立生产级应用的开发。它提供嵌入式服务器、安全性、监控等非功能特性,同时减少样板代码,使其成为构建 REST API 的理想选择。
在开始构建 REST API 之前,需准备以下环境:
使用 Spring Initializr 快速生成项目:
配置:
添加依赖:
.zip
文件。.zip
文件。典型项目结构如下:
src/main/java/com/example/restapi/
├── RestApiApplication.java // 主应用程序入口
├── model/ // 实体类
├── repository/ // 数据库交互接口
├── service/ // 业务逻辑层
├── controller/ // 控制器层
└── resources/application.properties // 配置文件
以管理 Product
实体为例:
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
}
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 > {
}
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);
}
}
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();
}
}
Spring Boot 提供注解处理常用 HTTP 请求:
通过全局异常处理器提供一致的错误响应:
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);
}
}
mvn clean package
java -jar target/restapi-0.0.1-SNAPSHOT.jar
通过本指南,您掌握了使用 Java Spring Boot 构建 REST API 的核心步骤:
Spring Boot 提供了强大的生态系统和社区支持,使其成为构建企业级 RESTful 服务的理想选择。