核心概念

  1. @RestController:组合注解,包含@Controller和@ResponseBody,用于定义RESTful控制器
  2. @GetMapping:HTTP GET请求映射注解
  3. SpringApplication:Spring Boot应用的启动入口
  4. 自动配置:Spring Boot根据依赖自动配置应用(如内嵌Tomcat)

详细操作步骤

环境准备

  1. JDK 17+(Spring Boot 3.x要求)
  2. Maven 3.6+ 或 Gradle
  3. IDE(IntelliJ IDEA推荐)

步骤1:创建项目(使用Spring Initializr)

  1. 访问 https://start.spring.io
  2. 选择:
    • Project: Maven
    • Language: Java
    • Spring Boot: 3.2.0+
    • Group: com.example
    • Artifact: demo
    • Dependencies: Spring Web
  3. 点击"Generate"下载项目

步骤2:导入项目

  1. 解压zip文件
  2. 在IDE中:File > Open > 选择pom.xml

步骤3:创建Controller

src/main/java/com/example/demo中创建HelloController.java

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController // 声明为REST控制器
public class HelloController {

    // 处理GET请求,路径为/hello
    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello, Spring Boot World!";
    }
}

步骤4:启动应用

  1. 打开主应用类DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // 核心启动注解
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args); // 启动Spring应用
    }
}
  1. 右键运行main()方法

步骤5:测试接口

  1. 浏览器访问:http://localhost:8080/hello
  2. 使用curl测试:
curl http://localhost:8080/hello
  1. 预期输出:Hello, Spring Boot World!

常见错误及解决方案

  1. 404 Not Found

    • ✅ 检查URL路径是否正确(区分大小写)
    • ✅ 确认Controller在启动类同级或子包下
    • ✅ 重启应用(IDE可能未自动编译)
  2. Whitelabel Error Page

    • ✅ 检查方法是否添加了@GetMapping@RequestMapping
    • ✅ 确保方法返回String类型(非void)
  3. 端口冲突

    # application.properties中添加
    server.port=8081
    
  4. 注解失效

    • ✅ 检查是否误用@Controller代替@RestController
    • ✅ Maven依赖是否完整(检查pom.xml)

注意事项

  1. 包扫描规则

    • 启动类会扫描同级及子包中的组件
    • 若Controller在不同包,需添加@ComponentScan
  2. HTTP方法注解

    • GET: @GetMapping
    • POST: @PostMapping
    • PUT: @PutMapping
    • DELETE: @DeleteMapping
  3. 路径规范

    • 统一使用小写+连字符(如/user-orders
    • 版本控制:/api/v1/hello

使用技巧

  1. 热部署(开发阶段):

    <!-- pom.xml添加 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    
  2. 自定义响应

    @GetMapping("/greet")
    public ResponseEntity<String> greet() {
        return ResponseEntity.ok()
                .header("X-Custom-Header", "value")
                .body("Custom response");
    }
    
  3. 路径参数

    @GetMapping("/user/{id}")
    public String getUser(@PathVariable String id) {
        return "User ID: " + id;
    }
    

最佳实践

  1. 分层结构

    ├── controller
    ├── service
    ├── repository
    └── model
    
  2. 统一响应格式

    public class ApiResponse<T> {
        private int code;
        private String message;
        private T data;
        // 构造方法/getter/setter
    }
    
  3. 全局异常处理

    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(Exception.class)
        public ResponseEntity<ApiResponse<?>> handleException(Exception ex) {
            // 返回统一错误格式
        }
    }
    

性能优化

  1. 线程池配置(application.properties):

    server.tomcat.threads.max=200
    server.tomcat.threads.min-spare=10
    
  2. 启用压缩

    server.compression.enabled=true
    server.compression.mime-types=text/html,text/xml,text/plain,application/json
    
  3. 连接超时设置

    server.tomcat.connection-timeout=5s
    
  4. 禁用不必要的自动配置

    @SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        SecurityAutoConfiguration.class
    })
    

完整项目结构示例

demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/example/demo/
│   │   │       ├── controller/
│   │   │       │   └── HelloController.java
│   │   │       ├── Application.java  // 启动类
│   │   ├── resources/
│   │   │   ├── application.properties
│   ├── test/  // 测试代码

通过这个指南,你已掌握Spring Boot创建REST接口的核心技能。下一步建议尝试:

  1. 添加POST请求处理
  2. 集成数据库(JPA)
  3. 实现简单的用户认证(Spring Security)
  4. 编写单元测试(MockMvc)