快速开始
本篇带你在 5 分钟内创建并运行第一个 Spring Boot 应用,并暴露一个 REST 接口。
环境要求
| 工具 | 版本要求 |
|---|---|
| JDK | 17+(Spring Boot 3.x 强制要求 JDK 17) |
| Maven | 3.6+(或使用 Gradle) |
| IDE | IntelliJ IDEA / VS Code 均可 |
方式一:Spring Initializr 创建项目(推荐)
- 打开 https://start.spring.io
- 选择:
- Project:Maven
- Language:Java
- Spring Boot:3.x 稳定版
- Group / Artifact:如
com.example/demo - Dependencies:添加
Spring Web
- 点击 Generate 下载压缩包,解压后用 IDE 打开。
方式二:手动编写 pom.xml
核心依赖如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
spring-boot-starter-parent 统一管理依赖版本;spring-boot-starter-web 引入 Spring MVC + 内嵌 Tomcat。
编写启动类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication 是组合注解,包含自动装配与组件扫描能力,详见核心注解。
编写第一个接口
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
启动与验证
# Maven
./mvnw spring-boot:run
# 或打包后运行
./mvnw clean package
java -jar target/demo-0.0.1-SNAPSHOT.jar
启动成功后访问:
curl http://localhost:8080/hello
# Hello, Spring Boot!
启动流程简述
main()
└── SpringApplication.run()
├── 创建 ApplicationContext(IoC 容器)
├── 加载自动配置(META-INF/spring/...AutoConfiguration.imports)
├── 组件扫描并注册 Bean
├── 启动内嵌 Tomcat(默认端口 8080)
└── 就绪,接收请求
提示
修改端口:在 application.properties 中配置 server.port=9090 即可。