> 技术文档 > Spring Boot 接口开发实战指南_springboot接口

Spring Boot 接口开发实战指南_springboot接口


Spring Boot 接口开发实战指南

一、基础接口开发步骤

1.1 添加必要依赖

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>

1.2 创建第一个REST接口

@RestController@RequestMapping(\"/api/v1\")public class HelloController { // 简单GET请求 @GetMapping(\"/hello\") public String sayHello() { return \"Hello Spring Boot!\"; } // 带路径参数的GET请求 @GetMapping(\"/users/{id}\") public ResponseEntity<User> getUser(@PathVariable Long id) { User user = userService.findById(id); return ResponseEntity.ok(user); }}

二、核心注解详解

2.1 常用注解对照表

注解 作用 示例场景 @RestController 组合注解(@Controller + @ResponseBody) REST接口类声明 @RequestMapping 定义请求映射基础路径 类级别路径定义 @GetMapping 处理GET请求 查询操作 @PostMapping 处理POST请求 新增操作 @PutMapping 处理PUT请求 更新操作 @DeleteMapping 处理DELETE请求 删除操作 @RequestBody 绑定请求体到方法参数 接收JSON请求体 @RequestParam 绑定查询参数到方法参数 分页参数接收

2.2 参数接收方式对比

// 路径参数@GetMapping(\"/products/{productId}\")public Product getProduct(@PathVariable String productId) { ... }// 查询参数@GetMapping(\"/search\")public List<Product> searchProducts( @RequestParam String keyword, @RequestParam(defaultValue = \"0\") int page, @RequestParam(defaultValue = \"10\") int size) { ... }// 请求体参数@PostMapping(\"/orders\")public Order createOrder(@Valid @RequestBody OrderDTO orderDTO) { ... }// 文件上传@PostMapping(\"/upload\")public String handleFileUpload(@RequestParam(\"file\") MultipartFile file) { ... }

三、接口响应规范

3.1 统一响应格式

public class ApiResponse<T> { private int code; private String message; private T data; private long timestamp = System.currentTimeMillis(); // 成功响应工厂方法 public static <T> ApiResponse<T> success(T data) { return new ApiResponse<>(200, \"Success\", data); } // 构造器、Getter/Setter省略}

3.2 响应状态码处理

@PostMapping(\"/users\")public ResponseEntity<ApiResponse<User>> createUser(@Valid @RequestBody User user) { User createdUser = userService.create(user); return ResponseEntity .status(HttpStatus.CREATED) .body(ApiResponse.success(createdUser));}

四、接口验证与异常处理

4.1 参数校验示例

public class UserDTO { @NotBlank(message = \"用户名不能为空\") @Size(min = 3, max = 20, message = \"用户名长度3-20个字符\") private String username; @Email(message = \"邮箱格式不正确\") private String email; // Getter/Setter}@PostMapping(\"/register\")public ApiResponse<User> register(@Valid @RequestBody UserDTO userDTO) { // 业务处理}

4.2 全局异常处理

@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ApiResponse<Map<String, String>> handleValidationExceptions( MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach(error -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return ApiResponse.error(400, \"参数校验失败\", errors); } @ExceptionHandler(Exception.class) public ApiResponse<String> handleAllExceptions(Exception ex) { return ApiResponse.error(500, \"服务器内部错误\", ex.getMessage()); }}

五、接口安全增强

5.1 JWT认证集成

@PostMapping(\"/login\")public ApiResponse<String> login(@RequestBody LoginRequest request) { if (authService.authenticate(request)) { String token = JwtUtil.generateToken(request.getUsername()); return ApiResponse.success(token); } return ApiResponse.error(401, \"认证失败\");}@GetMapping(\"/profile\")public ApiResponse<UserProfile> getProfile( @RequestHeader(\"Authorization\") String token) { String username = JwtUtil.validateToken(token); UserProfile profile = userService.getProfile(username); return ApiResponse.success(profile);}

5.2 接口限流配置

@Configurationpublic class RateLimitConfig { @Bean public FilterRegistrationBean<RateLimitFilter> rateLimitFilter() { FilterRegistrationBean<RateLimitFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(new RateLimitFilter(100)); // 100请求/秒 registration.addUrlPatterns(\"/api/*\"); return registration; }}

六、接口文档生成

6.1 Swagger集成配置

@Configuration@OpenAPIDefinition(info = @Info( title = \"电商平台API文档\", version = \"1.0\", description = \"电商平台接口文档\"))public class SwaggerConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .components(new Components()) .info(new Info().title(\"电商平台API文档\")); }}

6.2 接口注解示例

@Operation(summary = \"获取用户详情\")@ApiResponses(value = { @ApiResponse(responseCode = \"200\", description = \"成功获取用户信息\"), @ApiResponse(responseCode = \"404\", description = \"用户不存在\")})@GetMapping(\"/users/{id}\")public ResponseEntity<User> getUser( @Parameter(description = \"用户ID\") @PathVariable Long id) { // ...}

七、接口测试方法

7.1 Postman测试示例

POST http://localhost:8080/api/v1/loginContent-Type: application/json{ \"username\": \"testuser\", \"password\": \"Test123!\"}

7.2 单元测试示例

@SpringBootTest@AutoConfigureMockMvcclass UserControllerTest { @Autowired private MockMvc mockMvc; @Test void testGetUser() throws Exception { mockMvc.perform(get(\"/api/v1/users/1\") .header(\"Authorization\", \"Bearer valid_token\")) .andExpect(status().isOk()) .andExpect(jsonPath(\"$.data.username\").value(\"testuser\")); }}

最佳实践总结

  1. 版本控制:接口路径包含版本号(如/api/v1
  2. 统一响应:使用标准化的响应格式
  3. 参数校验:结合Validation API进行严格校验
  4. 文档维护:集成Swagger等文档工具
  5. 安全防护:添加JWT认证和接口限流
  6. 异常处理:全局异常捕获与友好提示
  7. 测试覆盖:编写单元测试和集成测试

扩展学习

  • Spring官方REST文档
  • RESTful API设计规范