Spring Boot 以「約定優於配置」聞名,官方提供 Spring Initializr 線上生成空白項目,幾分鐘即可跑通第一個服務。本文記錄從網頁填單到 IDEA 導入運行的完整流程。
| 字段 | 推薦值/說明 |
|---|---|
| Project | Maven Project(主流,Gradle 可選) |
| Language | Java |
| Spring Boot | 選穩定版(如 3.2.x / 2.7.x LTS) |
| Group | 組織域名倒序,如 com.example |
| Artifact | 項目名,如 demo |
| Name / Description | 自動填充,可修改 |
| Package name | 自動合成 Group + Artifact,如 com.example.demo |
| Packaging | Jar(內嵌容器)或 War(外部容器) |
| Java | 17 / 21 (LTS) 或 8(舊項目) |
在 Dependencies 搜索框輸入 Web,勾選 Spring Web(包含內嵌 Tomcat + Spring MVC + Jackson)。
常用組合:
- Spring Web + Lombok + Spring Boot DevTools(開發期熱部署)
- MySQL Driver + MyBatis / JPA(持久層)
- Spring Data Redis、Spring Cloud Starter 等按需添加
demo.zipFile → Open 選中解壓目錄下的 pom.xml,選 Open as Project@SpringBootApplication 的主類(如 DemoApplication),右鍵 Run . ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.2.0)
2024-01-15T10:30:45.123+08:00 INFO 12345 --- [ main] c.e.demo.DemoApplication : Starting DemoApplication using Java 17.0.9 with PID 12345
2024-01-15T10:30:45.125+08:00 INFO 12345 --- [ main] c.e.demo.DemoApplication : No active profile set, falling back to default profiles: default
2024-01-15T10:30:46.456+08:00 INFO 12345 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2024-01-15T10:30:46.789+08:00 INFO 12345 --- [ main] c.e.demo.DemoApplication : Started DemoApplication in 2.345 seconds (process running for 2.876)
關鍵標誌:Tomcat initialized with port(s): 8080 (http)、Started ... in X seconds。
https://localhost:8080 → 預期 404(無 Controller),但說明容器已啟動spring-boot-starter-actuator):https://localhost:8080/actuator/health → {"status":"UP"}@RestController
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
public String hello(@RequestParam(defaultValue = "World") String name) {
return "Hello, " + name + "! From Spring Boot.";
}
}
重啟應用,訪問 https://localhost:8080/api/hello?name=Boot 即見返回。
application.yml 加 server.port: 8081 或殺掉佔用進程Project Structure → Project → SDK 與 pom.xml <java.version> 一致settings.xml <mirror>)spring-boot-maven-plugin 存在並執行 mvn package