
如何利用API找回被盜的自行車
在開始構(gòu)建 REST API 之前,需準(zhǔn)備以下環(huán)境:
使用 Spring Initializr 快速生成項(xiàng)目:
配置:
添加依賴:
.zip
文件。.zip
文件。典型項(xiàng)目結(jié)構(gòu)如下:
src/main/java/com/example/restapi/
├── RestApiApplication.java // 主應(yīng)用程序入口
├── model/ // 實(shí)體類
├── repository/ // 數(shù)據(jù)庫交互接口
├── service/ // 業(yè)務(wù)邏輯層
├── controller/ // 控制器層
└── resources/application.properties // 配置文件
以管理 Product
實(shí)體為例:
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 請(qǐng)求:
通過全局異常處理器提供一致的錯(cuò)誤響應(yīng):
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 構(gòu)建 REST API 的核心步驟:
Spring Boot 提供了強(qiáng)大的生態(tài)系統(tǒng)和社區(qū)支持,使其成為構(gòu)建企業(yè)級(jí) RESTful 服務(wù)的理想選擇。
Index.dev: Build REST API with Java Spring Boot
如何利用API找回被盜的自行車
如何獲取tavily搜索API平臺(tái)秘鑰(分步指南)
什么是 API 即服務(wù)?
API可觀察性:需要監(jiān)控的5個(gè)指標(biāo)
性能優(yōu)化必讀:API性能測(cè)試的步驟和工具
身份證OCR識(shí)別API在Java、Python、PHP中的使用教程
輕松翻譯網(wǎng)頁內(nèi)容:Python 實(shí)現(xiàn) kimi網(wǎng)頁版 翻譯功能
API 監(jiān)控與指標(biāo)儀表盤:保障系統(tǒng)平穩(wěn)運(yùn)行的核心實(shí)踐
十大 API 安全供應(yīng)商
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)