第一个 Spring Boot 项目¶
亲手创建一个 Spring Boot 项目,跑通第一个接口。
创建项目的两种方式¶
方式一:start.spring.io(网页生成)
- 打开 start.spring.io;
- 选 Maven、Java 8、Spring Boot 2.7.18;
- 添加依赖:Spring Web、Validation、MySQL Driver;
- 生成下载,解压即用。
方式二:IDEA
New Project → Spring Initializr,同样的选项,IDEA 里点几下就行。
本书的
code/task-manager/就是这样一个项目,可以直接用。
pom.xml:依赖清单¶
对标前端的 package.json。本书 task-manager 的关键依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version> <!-- Spring Boot 版本,统一管理所有子依赖版本 -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <!-- Web:REST + 内置 Tomcat -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <!-- 参数校验 -->
</dependency>
<!-- MyBatis-Plus、MySQL、JWT 等见各自章节 -->
</dependencies>
starter 是什么
spring-boot-starter-web 是个"大礼包",一个依赖拉进来 Web 开发要的一堆东西(Tomcat、Spring MVC、Jackson)。对标前端:像 @vue/xxx 这种把相关功能打包好的依赖。
启动类¶
一个 Spring Boot 应用就从这个 main 方法启动:
package com.javaglm.task;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 任务管理系统 · 启动入口。
*
* <p>对标前端:这相当于 Vue 项目的 main.js 里 createApp(App).mount('#app') 的"启动点"。
* 一个 Spring Boot 应用从这个带 @SpringBootApplication 的 main 方法启动。
*
* <p>@MapperScan:告诉 MyBatis-Plus 去这个包下扫描 Mapper 接口(第 26 章)。
*
* <p>运行:IDEA 点运行按钮,或 mvn spring-boot:run。启动后监听 http://localhost:8080
*/
@SpringBootApplication
@MapperScan("com.javaglm.task.mapper")
public class TaskManagerApplication {
public static void main(String[] args) {
SpringApplication.run(TaskManagerApplication.class, args);
}
}
@SpringBootApplication= 自动配置 + 组件扫描 + 启动入口,三合一。- 对标前端:相当于
createApp(App).mount('#app')的启动点。
第一个接口¶
package com.javaglm.task.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 健康检查接口 · 骨架。
*
* <p>对标前端:{@code @RestController} 就像一个"路由 + 自动把返回值转成 JSON"的处理器。
* 访问 GET http://localhost:8080/health 会拿到一段 JSON。
*
* <p>真实的任务 CRUD / 登录认证接口在第三篇第 28、29 章逐步实现。
*/
@RestController
public class HealthController {
@GetMapping("/health")
public Map<String, Object> health() {
Map<String, Object> result = new HashMap<>();
result.put("status", "UP");
result.put("service", "task-manager");
return result;
}
}
@RestController= 这个类处理 HTTP 请求,返回值自动转 JSON。@GetMapping("/health")= 注册一个GET /health路由。对标前端的 Express/Koa 路由。- 返回
Map,Spring 自动用 Jackson 序列化成 JSON。
运行¶
浏览器或 Postman 访问 http://localhost:8080/health,会看到:
首次运行需要数据库
完整的 task-manager 配了 MySQL 数据源(第 25 章)。如果还没建库,启动会报连接错误。
先按第 27 章建好 task_manager 库和表,改好 application.yml 的密码,再运行。
:octicons-arrow-left-16: 上一章:IoC 与 DI | 下一章:REST 与分层架构