Spring Boot 接口开发实战指南

Spring Boot 接口开发实战指南

一、基础接口开发步骤

1.1 添加必要依赖

xml 复制代码
<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

1.2 创建第一个REST接口

java 复制代码
@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 参数接收方式对比

java 复制代码
// 路径参数
@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 统一响应格式

java 复制代码
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 响应状态码处理

java 复制代码
@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 参数校验示例

java 复制代码
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 全局异常处理

java 复制代码
@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认证集成

java 复制代码
@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 接口限流配置

java 复制代码
@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集成配置

java 复制代码
@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 接口注解示例

java 复制代码
@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测试示例

http 复制代码
POST http://localhost:8080/api/v1/login
Content-Type: application/json

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

7.2 单元测试示例

java 复制代码
@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. 测试覆盖:编写单元测试和集成测试

扩展学习:

复制代码
相关推荐
货拉拉技术6 小时前
构建稳定的 AI Agent:Harness 工程的核心机制与实践思考
人工智能·后端·数据分析
caoerzhong6 小时前
跨境海外仓怎么管:JeeWMS 开源 Java 仓库管理系统打通头程、海外仓与尾程
java·开发语言·开源
MayBaymax6 小时前
Elasticsearch 原理与用法
java·elasticsearch
hsfxuebao6 小时前
Harness工程
后端·架构
马剑威(威哥爱编程)6 小时前
【AI全栈后端12-02】Spring Boot 跑通第一个 AI 对话接口:HR 政策问答机器人实战
java·人工智能·spring boot·机器人
暗夜行者之光6 小时前
LangGraph 实战:构建“自我修正”的代码生成 Agent
后端
IT枫斗者枫哥6 小时前
AI返回合法JSON,字段就可信吗?给抽取结果补一道业务校验
java·人工智能·后端
用户3126874877206 小时前
Java IO/NIO/AIO 演进:从 BIO 到 Netty 的底层逻辑
java
IT枫斗者枫哥6 小时前
同一个requestId换了参数,为什么不能直接返回旧结果?
java·后端
天天被压力6 小时前
【别再到处找免费股票数据API了:官方204个接口,32篇一次讲透 #06】Python实时行情总报错?五档盘口+逐笔一次跑通
java·人工智能·python