SpringBoot 教程之 banner 定製

簡介

Spring Boot 啓動時默認會顯示如下 LOGO:html

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)

實際上,Spring Boot 支持自定義 logo 的功能。java

讓咱們來看看如何實現的。git

只要你在 resources 目錄下放置名爲 banner.txtbanner.gifbanner.jpgbanner.png 的文件,Spring Boot 會自動加載,將其做爲啓動時打印的 logo。github

  • 對於文本文件,Spring Boot 會將其直接輸出。
  • 對於圖像文件( banner.gifbanner.jpgbanner.png ),Spring Boot 會將圖像轉爲 ASCII 字符,而後輸出。

變量

banner.txt 文件中還能夠使用變量來設置字體、顏色、版本號。spring

變量 描述
${application.version} MANIFEST.MF 中定義的版本。如:1.0
${application.formatted-version} MANIFEST.MF 中定義的版本,並添加一個 v 前綴。如:v1.0
${spring-boot.version} Spring Boot 版本。如:2.1.1.RELEASE.
${spring-boot.formatted-version} Spring Boot 版本,並添加一個 v 前綴。如:v2.1.1.RELEASE
${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME}) ANSI 顏色、字體。更多細節,參考:AnsiPropertySource
${application.title} MANIFEST.MF 中定義的應用名。

示例:編程

在 Spring Boot 項目中的 resources 目錄下添加一個名爲 banner.txt 的文件,內容以下:app

${AnsiColor.BRIGHT_YELLOW}${AnsiStyle.BOLD}
 ________  ___  ___  ________   ___       __   ___  ___
|\   ___ \|\  \|\  \|\   ___  \|\  \     |\  \|\  \|\  \
\ \  \_|\ \ \  \\\  \ \  \\ \  \ \  \    \ \  \ \  \\\  \
 \ \  \ \\ \ \  \\\  \ \  \\ \  \ \  \  __\ \  \ \  \\\  \
  \ \  \_\\ \ \  \\\  \ \  \\ \  \ \  \|\__\_\  \ \  \\\  \
   \ \_______\ \_______\ \__\\ \__\ \____________\ \_______\
    \|_______|\|_______|\|__| \|__|\|____________|\|_______|
${AnsiBackground.WHITE}${AnsiColor.RED}${AnsiStyle.UNDERLINE}
:: Spring Boot ::             (v${spring-boot.version})
:: Spring Boot Tutorial ::    (v1.0.0)

注:${} 設置字體顏色的變量之間不能換行或空格分隔,不然會致使除最後一個變量外,都不生效。spring-boot

啓動應用後,控制檯將打印以下 logo:字體

<div align="center"><img src="http://dunwu.test.upcdn.net/snap/20181221231330.png!zp"/></div> 推薦兩個生成字符畫的網站,能夠將生成的字符串放入這個`banner.txt` 文件:網站

配置

application.properties 中與 Banner 相關的配置:

# banner 模式。有三種模式:console/log/off
# console 打印到控制檯(經過 System.out)
# log - 打印到日誌中
# off - 關閉打印
spring.main.banner-mode = off
# banner 文件編碼
spring.banner.charset = UTF-8
# banner 文本文件路徑
spring.banner.location = classpath:banner.txt
# banner 圖像文件路徑(能夠選擇 png,jpg,gif 文件)
spring.banner.image.location = classpath:banner.gif
used).
# 圖像 banner 的寬度(字符數)
spring.banner.image.width = 76
# 圖像 banner 的高度(字符數)
spring.banner.image.height =
# 圖像 banner 的左邊界(字符數)
spring.banner.image.margin = 2
# 是否將圖像轉爲黑色控制檯主題
spring.banner.image.invert = false

固然,你也能夠在 YAML 文件中配置,例如:

spring:
  main:
    banner-mode: off

編程

默認,Spring Boot 會註冊一個 SpringBootBanner 的單例 Bean,用來負責打印 Banner。

若是想徹底我的定製 Banner,能夠這麼作:先實現 org.springframework.boot.Banner#printBanner 接口來本身定製 Banner。在將這個 Banner 經過 SpringApplication.setBanner(…) 方法注入 Spring Boot。

示例

示例源碼:spring-boot-banner

參考資料

原文出處:https://www.cnblogs.com/jingmoxukong/p/10159493.html

相關文章
相關標籤/搜索