Spring Boot 通过 spring-boot-starter-web 内置 Tomcat 实现 REST 接口快速启动,配置 application.properties 即可调整端口、路径等,@RestController + @GetMapping 编写接口,注意 JSON 反序列化需字段名一致、无参构造函数及 @RequestBody 注解,启用 devtools 支持热更新。

用 Spring Boot 快速启动 REST 接口服务
不需要手动配 Tomcat、Servlet、web.xml,Spring Boot 内置了 Tomcat 和自动配置机制,spring-boot-starter-web 依赖一加,@RestController 一写,就能跑 HTTP 接口。
关键操作步骤:
- 用 start.spring.io 选中
Spring Web(即spring-boot-starter-web)生成项目 - 确保
pom.xml中有该依赖:org.springframework.boot spring-boot-starter-web - 主类上保留
@SpringBootApplication,启动类main方法运行后,默认监听http://localhost:8080 - 写一个最简接口:
@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, REST"; } }
端口、上下文路径等基础配置改哪里
所有运行时配置都集中在 application.properties 或 application.yml,不是改代码也不是改 IDE 设置。
常见配置项(以 application.properties 为例):
立即学习“Java免费学习笔记(深入)”;
-
server.port=8081:改默认 8080 端口 -
server.servlet.context-path=/api:所有接口前自动加/api,比如@GetMapping("/users")实际访问路径是/api/users -
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss:统一 JSON 时间格式输出 -
logging.level.org.springframework.web=DEBUG:开启请求日志,能看到每次 HTTP 方法、路径、参数、响应状态
接收 JSON 请求体时 400 或 415 错误怎么解
典型现象:Postman 发 Content-Type: application/json,但后端方法参数为 @RequestBody User user,却报 400 Bad Request 或 415 Unsupported Media Type。
根本原因和修复点:
- 确认前端发的 JSON 字段名和 Java Bean 的字段名**完全一致**(或已用
@JsonProperty显式映射),大小写敏感 - Bean 类必须有**无参构造函数**,否则 Jackson 反序列化失败
- 检查是否漏了
@RequestBody注解——仅当参数是 JSON body 时才需要它;查询参数仍用@RequestParam - 如果用了 Lombok,确保
@Data或@AllArgsConstructor+@NoArgsConstructor组合覆盖了无参构造 - 临时验证:把参数改成
@RequestBody String rawJson,打印出来看是否能收到原始 JSON 字符串,排除网络或客户端问题
开发阶段热更新不生效?别碰 spring-boot-devtools
IDEA 或 VS Code 修改 Java 文件后没自动重启,大概率是没启用热部署支持。
正确启用方式(Maven 项目):
- 在
pom.xml中添加:org.springframework.boot spring-boot-devtools runtime true - IDEA 需打开:
Settings → Build → Compiler → Build project automatically,再按Ctrl+Shift+Alt+/ → Registry → compiler.automake.allow.when.app.running勾上 - VS Code 用户需安装
Extension Pack for Spring Boot,并确保 Java 项目识别为 Spring Boot(有spring-boot-maven-plugin) - 注意:
devtools在打包成.jar后会自动禁用,不影响生产环境
真正麻烦的是静态资源(如 HTML、JS)修改后不刷新——Spring Boot 默认只监控 classpath:/static 下文件变动,且需浏览器手动 F5,LiveReload 需额外配 spring-boot-devtools + 浏览器插件,多数人其实只需要后端 Java 类热更。










