Spring Boot 學習 (四)自定義 Banner
SpringBoot應用程式啟動過程中,都會預設在控制檯輸出上圖所顯示的內容,即是我們本篇文章所說的Banner。
當然,SpringBoot 提供了預設的Banner之外,也提供了自定義設定Banner的功能。
1、自定義Banner內容
自定義Banner很簡單,只需要在 src/main/resource 下新建 banner.txt ,將我們的banner內容放到banner.txt裡面即可,啟動時SpringBoot會自動讀取並使用這個文字檔案中的banner。(banner.txt 也可以替換成 banner.gif , banner.jpg 或 banner.png 等圖片。圖片會轉換為字元畫(ASCII art)形式),同時存在多個banner檔案,啟動時會依次列印所有banner。
2、Banner樣式設定
如果我們是以 banner.txt 自定義Banner的話,我們可以在banner.txt 加入以下的一些佔位符樣式等屬性。
變數 | 描述 |
${Ansi.NAME}(或 |
|
${application.version} | MANIFEST.MF中宣告的應用版本號,例 如 Implementation-Version: 1.0 會 列印 1.0 |
${application.formatted-version} | MANIFEST.MF中宣告的被格式化後的應 用版本號(被括號包裹且以v作為前 綴),用於顯示,例如( v1.0 ) |
${spring-boot.version} | 當前Spring Boot的版本號,例 如 2.0.4.RELEASE |
${spring-boot.formatted-version} | 當前Spring Boot被格式化後的版本號 (被括號包裹且以v作為字首), 用於顯 示,例如( v2.0.0.RELEASE ) |
${application.title} | MANIFEST.MF 中宣告的應用title,例 如 Implementation-Title: MyApp 會 列印 MyApp |
示例:
banner.txt 內容加入 ${AnsiColor.Name} 設定banner顏色,加入${spring-boot.version}顯示當前SpringBoot版本號。
注:這裡 ${AnsiColor.Name}的作用範圍只對 ${AnsiColor.Name} 以下的內容有效。
執行效果:
3、通過程式設計方式實現Banner
除了建立banner檔案之外,spring boot 還提供了一個介面org.springframework.boot.Banner,它的例項可以被傳給SpringApplication的setBanner(banner)方法。我們只需要實現Banner介面的printBanner方法,並使用SpringBootApplication.setBanner(…) 方法設定我們自己的Banner例項即可。
4、關閉Banner
當然,如果我們不喜歡Banner的列印,也可以將其關閉。關閉方法如下:
1)在application.properties進行配置
spring.main.banner-mode=off
//spring.main.show-banner=false//已經過時
2)在SpringApplication中設定
public static void main(String[] args) {
SpringApplication application = new SpringApplication(HellospringbootApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}