第 44 章:第一个 REST + Maven
学习目标
- 用 Spring Initializr 创建项目
- 写第一个 REST 接口
- 学会 Maven 核心用法
一、创建项目
去 Spring Initializr 选:
| 项 | 值 |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.2.x |
| Java | 17 |
| Dependencies | Spring Web |
点 Generate,下载 zip 解压。
目录结构:
hello-rest/
├── pom.xml
└── src/main/java/com/example/hellorest/
└── HelloRestApplication.java二、第一个 REST 接口
java
// 启动类
@SpringBootApplication
public class HelloRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloRestApplication.class, args);
}
}
// Controller
@RestController // = @Controller + @ResponseBody,返回数据而不是页面
public class HelloController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, SpringBoot!";
}
}启动:HelloRestApplication.main() → 访问 http://localhost:8080/api/hello
三、常用注解
| 注解 | 作用 |
|---|---|
@RestController | 返回数据(等同 @Controller + @ResponseBody) |
@GetMapping("/x") | 处理 GET /x |
@PostMapping("/x") | 处理 POST /x |
@RequestMapping("/x") | 通用 |
@RequestParam | 读取 query 参数 |
@PathVariable | 读取路径参数 |
@RequestBody | 读取 JSON body |
java
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id,
@RequestParam(defaultValue = "10") int size) {
return userService.getById(id, size);
}
@PostMapping("/users")
public User createUser(@RequestBody @Valid User user) { // @Valid 校验
return userService.save(user);
}四、Maven 核心
4.1 pom.xml 结构
xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
<!-- ① 项目坐标 -->
<groupId>com.example</groupId>
<artifactId>hello-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- ② 父 POM:统一管理 SpringBoot 依赖版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 不用写版本,parent 统一管理 -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>4.2 常用命令
bash
./mvnw clean # 清理 target
./mvnw compile # 编译
./mvnw test # 跑测试
./mvnw spring-boot:run # 启动应用
./mvnw package -DskipTests # 打 jar,跳过测试4.3 依赖冲突
bash
./mvnw dependency:tree # 看依赖树
# 解决:排除传递依赖
<dependency>
<groupId>xxx</groupId>
<artifactId>yyy</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>⚠️ 坑 1:Spring Boot Starter 已经排掉 commons-logging(用 jcl-over-slf4j),所以你不需要再排除。盲目排除反而可能搞错。
五、配置文件
src/main/resources/application.yml:
yaml
server:
port: 8080
servlet:
context-path: /api
spring:
application:
name: hello-rest
profiles:
active: dev # 加载 application-dev.yml
# 自定义配置
app:
jwt:
secret: ${JWT_SECRET:default-dev-secret-32-bytes-long}
expire: 7200配置优先级(从高到低):
- 命令行参数
--server.port=9090 - 环境变量
SERVER_PORT=9090 application-{profile}.ymlapplication.yml
⚠️ 坑 2:配置是扁平化的,
a.b.c在 yml 里写a.b.c,不是a.b.c =一行。
六、多环境配置
resources/
├── application.yml # 公共
├── application-dev.yml # 开发
├── application-test.yml # 测试
└── application-prod.yml # 生产application-dev.yml:
yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_db
logging:
level:
com.example: DEBUG切换:spring.profiles.active=prod
七、运行方式
bash
# ① IDEA:右键 main 方法 → Run
# ② Maven 插件
./mvnw spring-boot:run
# ③ 打 Jar(部署用)
./mvnw package
java -jar target/hello-rest-0.0.1-SNAPSHOT.jar八、本章小结
| 要点 | 关键 |
|---|---|
| 启动类 | @SpringBootApplication + main |
| REST | @RestController + @GetMapping |
| 参数 | @RequestParam / @PathVariable / @RequestBody |
| Maven | 父 POM 统一版本,./mvnw spring-boot:run |
| 配置 | yml 扁平化,profile 区分环境 |
动手练习
- 创建项目,实现
GET /api/users/{id}返回 mock 用户 - 用
@RequestParam实现GET /api/search?keyword=xxx - 用
@RequestBody实现POST /api/users接收 JSON
下一章:第 45 章:项目结构与配置 →