Spring Boot 初级入门教程(五) —— 修改启动 Banner

Spring Boot 默认寻找 Banner 的顺序是:依次在 Classpath 下找文件 banner.gif , banner.jpg 和 banner.png , 先找到谁就用谁。如果没有,继续在 Classpath 下找 banner.txt。

上面都没有找到的话, 用默认的 SpringBootBanner , 就是我们最常见到的这个。

Spring Boot 项目启动时,默认的 Banner 显示如下:

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

如果同时存在图片(如 banner.jpg)和 banner.txt,则它们会同时显示出来, 先图片后文字。但同时存在多个图片,如 banner.(gif|jpg|png) , 则只会显示第一张图片。

如果想修改这个 Banner 文本显示,步骤如下:

一、在 resource 目录下创建 banner.txt 文件。

Spring Boot 初级入门教程(五) —— 修改启动 Banner_第1张图片

内容就是想定义的 Banner 样式。比如这里 banner.txt 的内容为如下:

                       d*##$.
 zP"""""$e.           $"    $o
4$       '$          $"      $
'$        '$        J$       $F
 'b        $k       $>       $
  $K        $r     J$       d$
  '$         $     $"       $~
   '$        "$   '$E       $
    $         $L   $"      $F ...
     $.       4B   $      $$$*"""*b
     '$        $.  $$     $$      $F
      "$       RS  $F     $"      $
       $k      ?$ u*     dF      .$
       ^$.      $$"     z$      u$$$$e
        #Sb             $E.dW@e$"    ?$
         #$           .o$$# d$$$$c    ?F
          $      .d$$#" . zo$>   #$r .uF
          $L .u$*"      $&$$$k   .$$d$$F
           $$"            ""^"$$$P"$P9$
          JP              .o$$$$u:$P $$
          $          ..ue$"      ""  $"
         d$          $F              $
         $$      ...udE             4B
          #$     """` $r            @$
           ^$L        '$            $F
             RN        4N           $
              *Sb                  d$
               $$k                 $F
                $$b                $F
                 $""               $F
                 '$                $
                  $L               $
                  '$               $
                   $               $

具体内容自己可以在以下网站去自定义,根据个人喜好。

网站一:http://www.network-science.de/ascii/

网站二:http://patorjk.com/software/taag/

二、启动程序,测试即可。

18:56:09,368 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
18:56:09,368 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
18:56:09,368 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/D:/workspace/workspace-sts-3.9.4.RELEASE-x86/test-springboot/target/classes/logback.xml]
18:56:09,424 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
18:56:09,425 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
18:56:09,431 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
18:56:09,434 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
18:56:09,459 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
18:56:09,460 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [baselog]
18:56:09,468 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@858242339 - No compression will be used
18:56:09,469 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@858242339 - Will use the pattern log/base.log.%d.%i for the active file
18:56:09,470 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4e1d422d - The date pattern is 'yyyy-MM-dd' from file name pattern 'log/base.log.%d.%i'.
18:56:09,470 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4e1d422d - Roll-over at midnight.
18:56:09,473 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4e1d422d - Setting initial period to Mon Jul 23 18:48:29 CST 2018
18:56:09,473 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4e1d422d - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead
18:56:09,473 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4e1d422d - For more information see http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy
18:56:09,475 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
18:56:09,479 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - Active log file name: log/base.log
18:56:09,479 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - File property is set to [log/base.log]
18:56:09,481 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
18:56:09,481 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
18:56:09,481 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.menglanglang.test.springboot] to DEBUG
18:56:09,481 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [baselog] to Logger[com.menglanglang.test.springboot]
18:56:09,481 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
18:56:09,482 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@66480dd7 - Registering current configuration as safe fallback point

                       d*##$.
 zP"""""$e.           $"    $o
4$       '$          $"      $
'$        '$        J$       $F
 'b        $k       $>       $
  $K        $r     J$       d$
  '$         $     $"       $~
   '$        "$   '$E       $
    $         $L   $"      $F ...
     $.       4B   $      $$$*"""*b
     '$        $.  $$     $$      $F
      "$       RS  $F     $"      $
       $k      ?$ u*     dF      .$
       ^$.      $$"     z$      u$$$$e
        #Sb             $E.dW@e$"    ?$
         #$           .o$$# d$$$$c    ?F
          $      .d$$#" . zo$>   #$r .uF
          $L .u$*"      $&$$$k   .$$d$$F
           $$"            ""^"$$$P"$P9$
          JP              .o$$$$u:$P $$
          $          ..ue$"      ""  $"
         d$          $F              $
         $$      ...udE             4B
          #$     """` $r            @$
           ^$L        '$            $F
             RN        4N           $
              *Sb                  d$
               $$k                 $F
                $$b                $F
                 $""               $F
                 '$                $
                  $L               $
                  '$               $
                   $               $

2018-07-23 18:56:09,879 INFO (StartupInfoLogger.java:50)- Starting App on LangLang-PC with PID 676 (D:\workspace\workspace-sts-3.9.4.RELEASE-x86\test-springboot\target\classes started by LangLang in D:\workspace\workspace-sts-3.9.4.RELEASE-x86\test-springboot)
2018-07-23 18:56:09,882 DEBUG (StartupInfoLogger.java:53)- Running with Spring Boot v2.0.2.RELEASE, Spring v5.0.6.RELEASE
2018-07-23 18:56:09,883 INFO (SpringApplication.java:659)- No active profile set, falling back to default profiles: default
2018-07-23 18:56:09,918 INFO (AbstractApplicationContext.java:590)- Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@10d17291: startup date [Mon Jul 23 18:56:09 CST 2018]; root of context hierarchy
2018-07-23 18:56:10,847 INFO (TomcatWebServer.java:91)- Tomcat initialized with port(s): 8080 (http)
2018-07-23 18:56:10,857 INFO (DirectJDKLog.java:180)- Initializing ProtocolHandler ["http-nio-8080"]
2018-07-23 18:56:10,863 INFO (DirectJDKLog.java:180)- Starting service [Tomcat]
2018-07-23 18:56:10,864 INFO (DirectJDKLog.java:180)- Starting Servlet Engine: Apache Tomcat/8.5.31
2018-07-23 18:56:10,868 INFO (DirectJDKLog.java:180)- The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\Java\x64\jdk1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:/Java/x86/jdk1.8.0_172/jre/bin/server;D:/Java/x86/jdk1.8.0_172/jre/bin;D:/Java/x86/jdk1.8.0_172/jre/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\Java\x86\jdk1.7.0_80\bin;D:\Java\x86\jdk1.7.0_80\lib;D:\apache-maven-3.3.9\bin;D:\instantclient_12_1;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;D:\Scala\scala-2.11.12\bin;D:\Hadoop\hadoop-2.5.1\bin;D:\Hadoop\hadoop-2.5.1\sbin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;D:\STS\x86\sts-bundle-3.9.4\sts-3.9.4.RELEASE;;.]
2018-07-23 18:56:10,934 INFO (DirectJDKLog.java:180)- Initializing Spring embedded WebApplicationContext
2018-07-23 18:56:10,934 INFO (ServletWebServerApplicationContext.java:285)- Root WebApplicationContext: initialization completed in 1016 ms
2018-07-23 18:56:11,041 INFO (ServletRegistrationBean.java:185)- Servlet dispatcherServlet mapped to [/]
2018-07-23 18:56:11,046 INFO (AbstractFilterRegistrationBean.java:244)- Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-23 18:56:11,046 INFO (AbstractFilterRegistrationBean.java:244)- Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-23 18:56:11,046 INFO (AbstractFilterRegistrationBean.java:244)- Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-23 18:56:11,046 INFO (AbstractFilterRegistrationBean.java:244)- Mapping filter: 'requestContextFilter' to: [/*]
2018-07-23 18:56:11,150 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-23 18:56:11,386 INFO (RequestMappingHandlerAdapter.java:574)- Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@10d17291: startup date [Mon Jul 23 18:56:09 CST 2018]; root of context hierarchy
2018-07-23 18:56:11,447 INFO (AbstractHandlerMethodMapping.java:547)- Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-23 18:56:11,449 INFO (AbstractHandlerMethodMapping.java:547)- Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-23 18:56:11,468 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-23 18:56:11,468 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-23 18:56:11,596 INFO (OptionalLiveReloadServer.java:57)- LiveReload server is running on port 35729
2018-07-23 18:56:11,618 INFO (MBeanExporter.java:433)- Registering beans for JMX exposure on startup
2018-07-23 18:56:11,633 INFO (DirectJDKLog.java:180)- Starting ProtocolHandler ["http-nio-8080"]
2018-07-23 18:56:11,685 INFO (DirectJDKLog.java:180)- Using a shared selector for servlet write/read
2018-07-23 18:56:11,710 INFO (TomcatWebServer.java:206)- Tomcat started on port(s): 8080 (http) with context path ''
2018-07-23 18:56:11,714 INFO (StartupInfoLogger.java:59)- Started App in 2.117 seconds (JVM running for 3.063)
Hello World!!!!

 通过上面的两步,其实 banner 已经修改完毕。如果想了解其它一些相关信息,可以往下看。

三、其它相关信息

1. 官网修改 banner 说明:

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath or by setting the spring.banner.location property to the location of such a file. If the file has an encoding other than UTF-8, you can set spring.banner.charset. In addition to a text file, you can also add a banner.gifbanner.jpg, or banner.png image file to your classpath or set the spring.banner.image.location property. Images are converted into an ASCII art representation and printed above any text banner.

翻译:可以通过将 banner.txt 文件添加到类路径或着将 spring.banner.location 属性设置为此文件的位置来更改启动时打印的 banner。如果文件的编码不是 UTF-8,则可以设置 spring.banner.charset。除了文本文件,还可以将 banner.gif,banner.jpg 或banner.png 图像文件添加到类路径或设置 spring.banner.image.location 属性。 图像将转换为 ASCII 艺术表示,并打印在任何文本 banner 上方。

2. 在 banner.txt 中,还可以使用变量占位符。

${spring-boot.version}:当前正在使用的 Spring Boot 版本, 如2.0.2.RELEASE。

${spring-boot.formatted-version}:当前正在使用的 Spring Boot版本,以格式化显示(用括号括起来并以 v 作为前缀), 例如(v2.0.2.RELEASE)。

${Ansi.NAME}:设置字体。

${AnsiColor.NAME}:设置字体颜色。(枚举值有:BLACK、BLUE、BRIGHT_BLACK、BRIGHT_BLUE、BRIGHT_CYAN、BRIGHT_GREEN、BRIGHT_MAGENTA、BRIGHT_RED、BRIGHT_WHITE、BRIGHT_YELLOW、CYAN、DEFAULT、GREEN、MAGENTA、RED、WHITE、YELLOW)

${AnsiBackground.NAME}:设置字体背景颜色。(枚举值有:BLACK、BLUE、BRIGHT_BLACK、BRIGHT_BLUE、BRIGHT_CYAN、BRIGHT_GREEN、BRIGHT_MAGENTA、BRIGHT_RED、BRIGHT_WHITE、BRIGHT_YELLOW、CYAN、DEFAULT、GREEN、MAGENTA、RED、WHITE、YELLOW)

${AnsiStyle.NAME}:设置字体风格。(枚举值有:BOLD、FAINT、ITALIC、NORMAL、UNDERLINE)

3. 实现接口,自定义 banner 样式。

package com.menglanglang.test.springboot;

import java.io.PrintStream;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

/**
 * @desc 应用入口
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2017年11月2日下午6:48:19
 */
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		// SpringApplication.run(App.class, args);
		// 自定义 banner 输出样式
		SpringApplication application = new SpringApplication(App.class);
		application.setBanner(new Banner() {
			@Override
			public void printBanner(Environment environment, Class sourceClass, PrintStream out) {
				//往 PrintStream 中输出,可从 Environment 中取属性配置
			}
		});
		// 设置 banner 显示位置,或者关闭 banner 显示
		application.setBannerMode(Banner.Mode.CONSOLE);// CONSOLE、LOG、OFF
		System.out.println("Hello World!!!!");
	}
}

4. 在 application.properties 中配置 banner 显示。

# BANNER
spring.banner.charset=UTF-8 # Banner file encoding.
spring.banner.location=classpath:banner.txt # Banner text resource location.
spring.banner.image.location=classpath:banner.gif # Banner image file location (jpg or png can also be used).
spring.banner.image.width=76 # Width of the banner image in chars.
spring.banner.image.height= # Height of the banner image in chars (default based on image height).
spring.banner.image.margin=2 # Left hand image margin in chars.
spring.banner.image.invert=false # Whether images should be inverted for dark terminal themes.

spring.main.banner-mode=console # Mode used to display the banner when the application runs.

Good Luck!

你可能感兴趣的:(Spring,Boot,Spring,boot,Spring,banner,框架,图文教程)