本文演示如何使用 Maven 從零構建一個基於 Spring Boot 1.4.3 的 Web 應用,涵蓋環境準備、POM 配置、依賴管理、代碼編寫、運行打包、IDE 推薦等全流程。
java -version, mvn -version<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<!-- 依賴將在這裡添加 -->
</project>
關鍵點:繼承 spring-boot-starter-parent 獲得預設依賴版本管理、插件配置、編碼 UTF-8、Java 6 編譯目標(可在 properties 覆蓋)。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
執行 mvn dependency:tree 可見傳遞依賴:Tomcat Embed、Spring MVC、Jackson、Hibernate Validator、Spring Core 等。
目錄結構:src/main/java/Example.java
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);
}
}
@RestController = @Controller + @ResponseBody,直接將返回值寫入 HTTP 響應體。@RequestMapping("/"):映射根路徑請求到 home() 方法。@EnableAutoConfiguration:啟用 Spring Boot 自動配置,檢測到 spring-boot-starter-web 後自動配置 Tomcat + Spring MVC。SpringApplication.run():啟動嵌入式容器,初始化 Spring 上下文。$ mvn spring-boot:run ... Started Example in 2.222 seconds (JVM running for 6.514)
瀏覽器訪問 https://localhost:8080/ 顯示 "Hello World!"。
添加打包插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
執行 mvn package,生成 target/myproject-0.0.1-SNAPSHOT.jar(包含所有依賴的 Fat JAR)。
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar ... Started Example in 2.536 seconds
sts-3.8.3.RELEASE。application.properties 添加 server.port=8081。spring-boot-devtools 依賴,配合 IDE 自動編譯實現修改即生效。application.yml/application.properties,多環境 application-dev.yml。@SpringBootTest + @AutoConfigureMockMvc 進行切面測試。org.springframework.boot 不變、配置鍵調整)。Spring Boot 的「約定優於配置」理念,讓開發者能專注於業務邏輯,快速交付生產級應用。