4

如何讓 Spring Boot 與 Maven 專案成功產製文件站台

 3 years ago
source link: https://blog.miniasp.com/post/2021/08/13/Spring-Boot-Maven-site-phase
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
如何讓 Spring Boot 與 Maven 專案成功產製文件站台

Apache Maven 有個 site 生命週期,定義出你要建立專案文件站台所需的各種階段,並讓你透過瀏覽器查看 Java 專案的完整資訊,相當方便。不過我透過 Spring Initializr 建立的專案,預設卻無法產生網站(site),錯誤訊息也有點奇怪,逼的我還要去研究 Maven 才終於理解錯誤的原因。這篇文章我就來交代正確的設定步驟與原理說明。

  1. 使用 Spring Initializr 工具建立一個以 Apache Maven 為主的 Spring Boot 專案

    在 Visual Studio Code 執行 F1 > Spring Initializr: Create a Maven Project 命令

    選擇 Spring Boot 版本: 2.5.3

    選擇程式語言: Java

    輸入 Group Id: com.duotify (通常會輸入一個組織名稱群組名稱)

    輸入 Artifact Id: demo1 (這裡要輸入一個應用程式的唯一名稱,這會決定最後封裝的檔名)

    選擇封裝方式: Jar

    選擇 Java 版本: 11

    選取相依套件: Spring Web, Lombok

    選擇一個資料夾: 假設我們選擇 g:\Projects 的話,他會自動建立一個 g:\Projects\<artifactId> 目錄,也就是 g:\Projects\demo1

    右下角會彈出通知訊息,請按下 Open 按鈕直接開啟 Java 專案!

  2. 開啟 pom.xml 並加入一個 maven-site-plugin 外掛 (Plugin)

    這裡最重要的設定,就是 <version> 標籤(Tag),一定要加上,否則執行 mvn site 就會失敗!

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-site-plugin</artifactId>
      <version>3.9.1</version>
    </plugin>
    
  3. 執行 mvn site 命令,產生專案文件的站台

    事實上這個命令會在 target/site 目錄下產生一個「網站」,裡面有多份 HTML 文件,也包含網頁所需的圖片、CSS、JS 等等,簡單來說,就是一個完整的網站!

    你可以利用 Live Preview 開啟 target/site/index.html 即可查看該專案的完整資訊。

    target/site/index.html

    你也可以執行 mvn site:run 啟動一個暫時的網站伺服器,預設會開 Port 8080,啟動後開啟瀏覽器到 http://localhost:8080 就可以瀏覽文件。

你從 Apache Maven 官網的 Lifecycles Reference 文件可以發現,Maven 在 META-INF/plexus/components.xml 定義了 3 個生命週期 (Lifecycles),其中一個 site 生命週期定義如下:

<phases>
  <phase>pre-site</phase>
  <phase>site</phase>
  <phase>post-site</phase>
  <phase>site-deploy</phase>
</phases>
<default-phases>
  <site>
    org.apache.maven.plugins:maven-site-plugin:3.3:site
  </site>
  <site-deploy>
    org.apache.maven.plugins:maven-site-plugin:3.3:deploy
  </site-deploy>
</default-phases>

你可以看到這裡有定義 4 個階段 (phase),而且其中兩個階段有設定預設目標 (default goal),其中 default-phases 定義的 site 預設目標設定到 org.apache.maven.plugins:maven-site-plugin:3.3:site,這個 org.apache.maven.plugins:maven-site-plugin:3.3:site 目標 (goal) 是這樣理解的:

  • org.apache.maven.pluginsgroupId
  • maven-site-pluginartifactId
  • 3.3version
  • sitegoal

這就意味著你必須加裝 maven-site-pluginpom.xml<plugins> 清單中,讓你在執行 site 階段 (phase) 的時候 (mvn site),才能夠「預設」觸發這個 site 目標。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK