首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring Boot 快速搭建完整指南:從零到 Hello World

     編輯:Java 綜合教學

Spring Boot 快速搭建完整指南:從零到 Hello World

Spring Boot 通過「約定優於配置」極大簡化了 Spring 應用的初始搭建過程。本文記錄基於 Maven 的標準項目創建全流程,涵蓋父 POM 繼承、依賴管理、啟動類編寫等核心環節。

環境準備與項目骨架

1. 繼承 spring-boot-starter-parent(推薦)

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.BUILD-SNAPSHOT</version>
</parent>

父 POM 提供的核心優勢:

  • 默認 Java 1.6 編譯級別、UTF-8 源碼編碼
  • 統一依賴版本管理(無需在常用 Starter 中聲明 version)
  • 資源過濾、插件配置(exec、surefire、Git commit ID、shade)開箱即用
  • 支持 application.properties/yml 佔位符解析

2. 不使用父 POM 的替代方案

<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 的場景,同樣享受依賴版本管控。

3. 修改 Java 版本

<properties>
    <java.version>1.8</java.version>
</properties>

添加 Web 開發依賴

<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

運行驗證

  1. 執行 main 方法啟動內嵌 Tomcat
  2. 瀏覽器訪問 https://localhost:8080
  3. 頁面顯示 Hello World! 表示成功

進階提示

  • 生產環境建議打包為可執行 JAR(mvn package)而非 WAR
  • 外部化配置優先級:命令行參數 > 環境變量 > application-{profile}.properties > application.properties
  • 啟用 Actuator 監控端點:添加 spring-boot-starter-actuator
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved