
如何利用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 服務的理想選擇。
Index.dev: Build REST API with Java Spring Boot