学习目标与前置
建议用时:60 分钟准备:JDK17+,Maven,IDEA
- 使用 Spring Initializr 生成项目并导入 IDEA。
- 理解 @SpringBootApplication、Starter、自动装配。
- 编写 @RestController 并返回 JSON。
- 通过 application.yaml 配置端口、应用名,启用 devtools 热部署。
Step 1:使用 Spring Initializr 生成项目
- 打开 start.spring.io。
- 选择:Project=Maven、Language=Java、Spring Boot=3.x、Packaging=Jar、Java=17。
- Dependencies 选择:Spring Web、Validation、Lombok、(可选) DevTools。
- 填写 Group(如
demo)、Artifact(如boot-demo),点击 Generate 下载。 - 解压后用 IDEA 打开该目录。
Step 2:项目结构与入口类
flowchart TD A[入口 DemoApplication] --> B[SpringApplication.run] B --> C[自动装配 AutoConfiguration] C --> D[内嵌 Tomcat 启动] D --> E[扫描组件 Controller/Service/...] E --> F[对外暴露 REST 接口]
src/main/java:业务代码;src/main/resources:配置文件。pom.xml:依赖与插件;application.yaml/properties:应用配置。
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
注:@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan。
Step 3:编写第一个 Controller
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public Map<String, Object> hello(@RequestParam(defaultValue = "world") String name) {
return Map.of("msg", "Hello " + name);
}
}
说明:@RestController = @Controller + @ResponseBody;@RequestParam 读取查询参数。
Step 4:配置 application.yaml
server:
port: 8080
spring:
application:
name: boot-demo
devtools:
restart:
enabled: true
保存后,重启或由 devtools 自动重启生效。
Step 5:运行与热部署
- 在 IDEA 右上角运行 DemoApplication,访问
http://localhost:8080/api/hello。 - 修改返回内容,保存,观察 devtools 是否自动重启;刷新浏览器验证。
- 若端口被占用,改 application.yaml 的 port,重启。
Starter 与自动装配要点
- starter(如 spring-boot-starter-web)是依赖集合,内含 Spring MVC、内嵌 Tomcat、JSON 序列化。
- 自动装配:根据 classpath + 配置文件加载 Bean;可引入 spring-boot-starter-actuator 并查看
/actuator/beans。
常见问题与排查
- 端口被占用:修改 server.port 或关闭占用进程。
- 热部署不生效:确认引入 devtools,且未在生产环境运行;IDEA 需开启自动构建(Settings → Compiler → Build project automatically)。
- 404:检查 @RequestMapping 路径;确认应用是否启动成功(控制台无异常)。
课堂练习
- 新增 GET /api/ping 返回
{"ok":true}。 - 使用 @Value 读取自定义配置
demo.welcome,在返回结果中输出。
课后巩固
- 添加 actuator 依赖,调用
/actuator/health并截图。 - 在 README 记录启动命令、端口、常用配置项;说明 devtools 注意事项。