Contents

Spring Boot 設定啟動時 Banner

最近在找 Spring Boot 設定,看到可以自訂啟動時的 Banner,覺得很有趣,記錄一下設定方式。

什麼是 Spring Boot Banner?

Spring Boot 應用程式啟動時,預設會在 Console 顯示一個 ASCII art 樣式的 Spring Boot Logo:

1
2
3
4
5
6
7
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v3.1.0)

你可以替換成自訂的 Banner,作為專案的標識或彩蛋。

方法一:文字 Banner(banner.txt)

src/main/resources/ 目錄下建立 banner.txt 檔案,Spring Boot 啟動時會自動讀取並顯示:

1
2
3
4
5
6
7
 __  __         _                   ____              _ 
|  \/  |_   _  / \   _ __  _ __   / ___|___  _ __ __| |
| |\/| | | | |/ _ \ | '_ \| '_ \ | |   / _ \| '__/ _` |
| |  | | |_| / ___ \| |_) | |_) || |__| (_) | | | (_| |
|_|  |_|\__, /_/   \_\ .__/| .__/  \____\___/|_|  \__,_|
        |___/        |_|   |_|                           
:: My Application :: v1.0.0

banner.txt 中可以使用以下 Spring Boot 內建變數:

1
2
3
4
5
${application.version}           # 應用程式版本(來自 MANIFEST.MF)
${application.formatted-version} # 格式化版本(例如:v1.0.0)
${spring-boot.version}           # Spring Boot 版本
${spring-boot.formatted-version} # Spring Boot 格式化版本
${application.title}             # 應用程式名稱

範例 banner.txt

1
2
3
4
5
6
7
8
  __  __         _      ____              _ 
 |  \/  |_   _  / \    / ___|___  _ __ __| |
 | |\/| | | | |/ _ \  | |   / _ \| '__/ _` |
 | |  | | |_| / ___ \ | |__| (_) | | | (_| |
 |_|  |_|\__, /_/   \_\ \____\___/|_|  \__,_|
         |___/
 
 Spring Boot ${spring-boot.formatted-version}

方法二:圖片 Banner(banner.gif / banner.jpg / banner.png)

Spring Boot 支援將圖片轉換為 ASCII art 作為 Banner:

  1. 將圖片(支援 GIF、JPEG、PNG)放到 src/main/resources/
  2. 命名為 banner.gifbanner.jpgbanner.png
  3. Spring Boot 會自動將圖片轉成 ASCII art 顯示

注意:不是所有圖片都適合,對比度高、有清晰輪廓的圖片效果較好。建議使用有框線包圍的圖示,純色照片或色彩複雜的圖片通常辨識度很低。

方法三:自訂 Banner 路徑

若要將 Banner 檔案放在非預設位置,在 application.properties 中指定路徑:

1
2
3
4
5
# 自訂文字 banner 路徑
spring.banner.location=classpath:custom/mybanner.txt

# 自訂圖片 banner 路徑
spring.banner.image.location=classpath:custom/logo.png

關閉 Banner

若不想顯示 Banner,可以:

方式一:application.properties

1
spring.main.banner-mode=off

方式二:程式碼設定

1
2
3
4
5
6
7
8
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
}

banner-mode 的選項:

  • console(預設):輸出到 Console
  • log:輸出到 Log
  • off:關閉 Banner

ASCII Art 生成工具

推薦以下工具將文字轉換為 ASCII Art:

  • Text to ASCII Art Generator(TAAG):https://patorjk.com/software/taag/
    • 支援多種字型,選好後複製貼到 banner.txt 即可
  • ASCII Art Archive:https://www.asciiart.eu/
    • 有大量現成的 ASCII Art 圖案

參考資料