Spring Boot 通過「約定優於配置」極大簡化了 Spring 應用的初始搭建過程。本文記錄基於 Maven 的標準項目創建全流程,涵蓋父 POM 繼承、依賴管理、啟動類編寫等核心環節。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.BUILD-SNAPSHOT</version>
</parent>
父 POM 提供的核心優勢:
application.properties/yml 佔位符解析<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
適用於企業強制統一父 POM 的場景,同樣享受依賴版本管控。
<properties>
<java.version>1.8</java.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 繼承父 POM 時可省略 version -->
</dependency>
package com.example.project; // 建議使用反轉域名包結構
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
| 規範 | 說明 |
|---|---|
| 避免默認包 | 無 package 聲明會導致 @ComponentScan 掃描所有 jar 類,引發錯誤 |
| 主類放在根包 | 便於 @SpringBootApplication 隱式定義基礎掃描路徑 |
| 使用 @SpringBootApplication | 組合了 @Configuration、@EnableAutoConfiguration、@ComponentScan |
main 方法啟動內嵌 Tomcathttps://localhost:8080Hello World! 表示成功mvn package)而非 WARspring-boot-starter-actuator