Spring Boot 接口开发实战指南

#新星杯·14天创作挑战营·第11期#

Spring Boot 接口开发实战指南

一、基础接口开发步骤

1.1 添加必要依赖

<!-- pom.xml -->
<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 全局异常处理

@RestControllerAdvice
public 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 接口限流配置

@Configuration
public 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/login
Content-Type: application/json

{
    "username": "testuser",
    "password": "Test123!"
}

7.2 单元测试示例

@SpringBootTest
@AutoConfigureMockMvc
class 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. 测试覆盖:编写单元测试和集成测试

扩展学习


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值