题目
Spring Boot中如何创建一个简单的RESTful API端点
信息
- 类型:问答
- 难度:⭐
考点
Spring Boot基础, RESTful API设计, 注解使用
快速回答
在Spring Boot中创建RESTful API端点的核心步骤:
- 使用
@RestController注解标记控制器类 - 在方法上添加
@GetMapping等HTTP方法注解 - 定义方法返回数据(自动转为JSON)
- 通过
@RequestMapping或方法注解指定URL路径
原理说明
Spring Boot通过注解驱动简化RESTful API开发:@RestController组合了@Controller和@ResponseBody,自动将方法返回值序列化为JSON。HTTP方法注解(如@GetMapping)映射URL到具体方法。
代码示例
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class DemoController {
// 处理GET请求 /api/greeting
@GetMapping("/greeting")
public String greeting() {
return "Hello, Spring Boot!";
}
// 带路径参数的GET请求 /api/user/123
@GetMapping("/user/{id}")
public String getUser(@PathVariable String id) {
return "User ID: " + id;
}
}最佳实践
- 使用统一API前缀(如
@RequestMapping("/api")) - 遵循RESTful命名规范(资源使用名词,如
/users) - 返回ResponseEntity对象可自定义HTTP状态码
- 对复杂对象直接返回,Spring Boot自动序列化为JSON
常见错误
- 忘记添加
@RestController导致返回视图名称 - URL路径冲突(多个方法映射相同路径)
- 未处理
@PathVariable参数导致404错误 - 未启动类添加
@SpringBootApplication注解
扩展知识
- 其他HTTP注解:
@PostMapping,@PutMapping,@DeleteMapping - 请求参数处理:
@RequestParam获取查询参数 - RequestBody:
@RequestBody接收JSON请求体 - 启动验证:访问
http://localhost:8080/api/greeting测试API