SpringBoot之自定义Banner详解

1、在线生成banner网站

https://www.bootschool.net/ascii
http://www.network-science.de/ascii/
http://patorjk.com/software/taag/
http://www.degraeve.com/img2txt.php

2、两种自定义Banner方式

在自定义Banner之前,先剖析一下源码,源码跟踪解析如下:

  • SpringBoot启动的main方法
public static void main(String[] args) {
		SpringApplication springApplication = new SpringApplication(Application.class);
		//开启Banner打印方式(OFF:关闭,CONSOLE:控制台输出,LOG:日志输出)
		springApplication.setBannerMode(Mode.LOG);
		springApplication.run(args);
	}
  • SpringApplication.printBanner():
private Banner printBanner(ConfigurableEnvironment environment) {
       //是否开启Banner模式
        if (this.bannerMode == Mode.OFF) {
            return null;
        } else {
            ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader((ClassLoader)null);
            SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter((ResourceLoader)resourceLoader, this.banner);
            return this.bannerMode == Mode.LOG ? bannerPrinter.print(environment, this.mainApplicationClass, logger) : bannerPrinter.print(environment, this.mainApplicationClass, System.out);
        }
    }
  • SpringApplicationBannerPrinter.print()
Banner print(Environment environment, Class<?> sourceClass, Log logger) {
	   //调用getBanner()方法
        Banner banner = this.getBanner(environment);
        try {
            logger.info(this.createStringFromBanner(banner, environment, sourceClass));
        } catch (UnsupportedEncodingException var6) {
            logger.warn("Failed to create String for banner", var6);
        }
        return new SpringApplicationBannerPrinter.PrintedBanner(banner, sourceClass);
    }
  • SpringApplicationBannerPrinter.getBanner()
private Banner getBanner(Environment environment) {
    SpringApplicationBannerPrinter.Banners banners = new SpringApplicationBannerPrinter.Banners();
    //先获取image类型的banner
    banners.addIfNotNull(this.getImageBanner(environment));
    //在获取text类型的banner
    banners.addIfNotNull(this.getTextBanner(environment));
    if (banners.hasAtLeastOneBanner()) {
        // 如果至少有一个,则返回
        // Banners 也实现了 Banner 接口,运用了组合模式,实际上可同时打印图片和文本 banner。
        return banners;
    } else {
         // 返回自定义的banner(this.fallbackBanner) 或者 springboot默认的banner(DEFAULT_BANNER)
         // 默认的banner类:SpringBootBanner。
         // 自定义的banner:需要我们仿照SpringBootBanner去自定义一个类

         //this.fallbackBanner: 表示自定义的banner,此参数可在springboot启动类的main方法中设置,后续会介绍

         //   public static void main(String[] args) {
         //        SpringApplication springApplication = new SpringApplication(Application.class);
         //        springApplication.setBanner(new MyBanner());//自定义的banner
         //        springApplication.run(args);
         //   }

          return this.fallbackBanner != null ? this.fallbackBanner : DEFAULT_BANNER;
    }
}

解释:banner的获取方式有两种,先获取image类型的banner,然后获取text类型的banner,如果至少有一个,则执行该banner,如果没有,返回自定义的banner,如果自定义也没有,则返回默认

那么上述源码中是如何获取image类型和Text类型的banner呢?
SpringApplicationBannerPrinter.getImageBanner()
SpringApplicationBannerPrinter.getTextBanner()

//获取Text类型的banner
private Banner getTextBanner(Environment environment) {
    //先从spring.banner.location路径中去取,如果没有,默认banner.txt
    String location = environment.getProperty("spring.banner.location", "banner.txt");
    Resource resource = this.resourceLoader.getResource(location);
    try {
        if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
            return new ResourceBanner(resource);
        }
    } catch (IOException var5) {}
    return null;
}

//获取image类型的banner
private Banner getImageBanner(Environment environment) {
    String location = environment.getProperty("spring.banner.image.location");
    if (StringUtils.hasLength(location)) {
        Resource resource = this.resourceLoader.getResource(location);
        return resource.exists() ? new ImageBanner(resource) : null;
    } else {
        String[] var3 = IMAGE_EXTENSION;
        int var4 = var3.length;
        for(int var5 = 0; var5 < var4; ++var5) {
            String ext = var3[var5];
            Resource resource = this.resourceLoader.getResource("banner." + ext);
            if (resource.exists()) {
                return new ImageBanner(resource);
            }
        }
        return null;
    }
}

基于图片的 banner

  • 可通过配置参数 spring.banner.image.location 来指定
  • 可将名为 “banner.jpg” (哪几种类型取决于ext常量的定义) 的文件放在classpath 目录(src/main/resources)

基于文件的 banner

  • 可通过配置参数 spring.banner.location 来指定
  • 可将名为 “banner.txt” 的文件放在 classpath 目录(src/main/resources)

源码分析完毕,那么如何去自定义呢?

第一种:配置方式(直接在properties或yml文件中进行配置)
即配置 spring.banner.image.location 和 spring.banner.location路径
或者
将 “图片” 和 “banner.txt” 放在classpath 目录中

spring.banner.location=classpath:banner1.png
spring.banner.image.margin=2
spring.banner.image.height=76
spring.banner.charset=UTF-8
spring.banner.image.invert=false
spring.banner.image.location=banner1.png
spring.main.banner-mode=console
spring.main.show-banner=true

第二种:自定义banner

import org.springframework.boot.Banner;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment;
import java.io.PrintStream;
/** 自定义banner类
 * @author hb
 * @date 2021-09-09 10:39
 */
public class MyBanner implements Banner {

    private static final String[] BANNER = new String[]{"", "  .   ____          _            __ _ _", " /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\", "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", " \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )", "  '  |____| .__|_| |_|_| |_\\__, | / / / /", " =========|_|==============|___/=/_/_/_/"};

    public MyBanner() {
    }

    @Override
    public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
        String[] bannerArray = BANNER;
        int bannerLength = bannerArray.length;
        for(int i = 0; i < bannerLength; ++i) {
            String line = bannerArray[i];
            out.println(line);
        }
        out.println(AnsiOutput.toString(new Object[]{AnsiColor.GREEN, " :: Spring Boot :: ", AnsiColor.DEFAULT,  AnsiStyle.FAINT}));
        out.println();
    }
}

如何使用自定义Banner?
springboot启动类中添加自定义banner

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
   public static void main(String[] args) {
      SpringApplication springApplication = new SpringApplication(Application.class);
      //添加自定义banner
      springApplication.setBanner(new MyBanner());
      springApplication.run(args);
   }
}

如果不想打印banner,可以在启动类的main中,设置 springApplication.setBannerMode(Banner.Mode.OFF);
或者
通过参数配置spring.main.banner-mode=off来关闭banner的打印

3、控制banner样式

Spring提供了三个枚举类来设定字符的颜色,分别是:

AnsiColor: 用来设定字符的前景色
AnsiBackground: 用来设定字符的背景色
AnsiStyle: 用来控制加粗、斜体、下划线等等。

4、显示应用信息

除了上面的指定样式之外,还可以显示一些与应用相关的版本信息:

${application.version}   与 MANIFEST.MF文件中相同的版本号,比如1.5.4.RELEASE
${application.formatted-version}   格式化过的版本号就是加个v然后用括号包起来,比如(v1.5.4.RELEASE)
${application.title}
${spring-boot.version} Spring Boot的版本
${spring-boot.formatted-version} 格式化过的版本

到此这篇关于SpringBoot之自定义Banner详解的文章就介绍到这了,更多相关SpringBoot之自定义Banner内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 教你怎么用Springboot自定义Banner图案

    一.前言 我们在启动 Spring Boot 项目时,默认会在控制台打印 Spring logo 和版本等信息,如下: 这就是 Spring Boot 的 Banner 打印功能,其实我们可以自定义打印的 banner ,也可以禁用和启用打印 banner 功能.在真实项目中,我们一般不会去自定义 banner 图案,它其实就是项目启动时打印图案或者文字而已,没实际意义.推荐在自己个人项目玩玩这个彩蛋即可,顺便简单了解下它内部实现原理. 比如,自定义一个 banner 之后,项目启动控制台打印如

  • SpringBoot之Banner的使用示例

    背景 初次运行SpringBoot的小伙伴想必对于SpringBoot打印的Banner很感兴趣 Spring Boot在启动项目时,控制台会打印一个Spring的logo.如果不做任何配置 该信息来源于SpringBootBanner类的静态常量BANNER,该属性是一个字符串数组,不指定任何banner属性时,控制台默认输出该数组数据.我们可以通过Spring Boot提供的强大配置功能来改变banner的输出. 通常长成这样 一个Spring扑面而来~ 那么我们能否定制自己的启动页呢? 源

  • 详解SpringBoot基础之banner玩法解析

    SpringBoot项目启动时会在控制台打印一个默认的启动图案,这个图案就是我们要讲的banner.看似简单的banner,我们能够对它做些什么呢?本篇文章就带大家深入了解一下banner的使用(版本:SpringBoot2.1.4). 制作自己的banner 第一步:在src/main/resources下面创建banner.txt. 第二步:访问网站 http://patorjk.com/software/taag,在网站"Type Something "处输入想要制作的单词(比如

  • 超个性修改SpringBoot项目的启动banner的方法

    如果我们使用过SpringBoot,那么就会对下面的图案不陌生.Springboot 启动的同时会打印下面的图案,并带有版本号. 查看SpringBoot官方文档可以找到关于 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 t

  • SpringBoot个性化启动Banner设置方法解析

    1.添加Banner.txt文件 . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: tianheng Sprin

  • SpringBoot之自定义Banner详解

    1.在线生成banner网站 https://www.bootschool.net/ascii http://www.network-science.de/ascii/ http://patorjk.com/software/taag/ http://www.degraeve.com/img2txt.php 2.两种自定义Banner方式 在自定义Banner之前,先剖析一下源码,源码跟踪解析如下: SpringBoot启动的main方法 public static void main(Stri

  • Java SpringBoot自定义starter详解

    目录 一.什么是SpringBoot starter机制 二.为什么要自定义starter ? 三.什么时候需要创建自定义starter? 四.自定义starter的开发流程(案例:为短信发送功能创建一个starter) 1.细节:命名规范 2.必须引入的依赖 3.编写相关属性类(XxxProperties):例如 SmsProperties.java 4.编写Starter项目的业务功能 5.编写自动配置类AutoConfig 6.编写spring.factories文件加载自动配置类 7.打

  • 使用SpringBoot自定义starter详解

    一.新建一个工程 工程由xxx-sprig-boot-starter和xxx-sprig-boot-starter-configure两个模块组成: xxx-sprig-boot-starter模块 只用来做依赖导入 依赖于 xxx-sprig-boot-starter-configure模块,没有实际代码 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave

  • SpringBoot使用Log4j过程详解

    这篇文章主要介绍了SpringBoot使用Log4j过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 log4j.logback.Log4j2简介 log4j是apache实现的一个开源日志组件 logback同样是由log4j的作者设计完成的,拥有更好的特性,用来取代log4j的一个日志框架,是slf4j的原生实现 Log4j2是log4j 1.x和logback的改进版,采用了一些新技术(无锁异步.等等),使得日志的吞吐量.性能比lo

  • SpringBoot登录拦截配置详解(实测可用)

    背景:写一个用户登录拦截,在网上找了一圈没找到好用的,于是自己试验了一下,总结出来,分享给大家. 1.自定义登录拦截器LoginInterceptor public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) thr

  • SpringBoot web静态资源配置详解

    引言: SpringBoot web项目开发中往往会涉及到一些静态资源的使用,比如说图片,css样式,js等等,今天我们来讲讲这些常见的静态资源应该放在哪个位置,怎么放在自己想放的位置. 1. 项目创建 我们先创建一个空的项目,项目的依赖配置为starter-web依赖,创建好的项目下面有一个resources文件夹,里面有一些空的默认的文件夹,然后有一个配置文件. templates文件下面一般是放置模板页面的,比如html,jsp之类的,static文件一般是是放置静态资源,比如说,图片,文

  • 10k+点赞的 SpringBoot 后台管理系统教程详解

    其实项目网上有很多了,但是教程比较详细的没多少,今天分享的项目从安装部署到代码具体功能都有很详细都说明 eladmin 是一款基于 Spring Boot 2.1.0 . Jpa. Spring Security.redis.Vue 的前后端分离的后台管理系统,项目采用分模块开发方式, 权限控制采用 RBAC,支持数据字典与数据权限管理,支持一键生成前后端代码,支持动态路由. 这个开源项目基本稳定,并且后续作者还会继续优化.完全开源!这个真的要为原作者点个赞,如果大家觉得这个项目有用的话,建议可

  • Java SpringBoot Validation用法案例详解

    目录 constraints分类 对象集成constraints示例 SpringBoot集成自动验证 集成maven依赖 验证RequestBody.Form对象参数 验证简单参数 验证指定分组 全局controller验证异常处理 自定义constraints @DateFormat @PhoneNo 使用自定义constraint注解 问题 提到输入参数的基本验证(非空.长度.大小.格式-),在以前我们还是通过手写代码,各种if.else.StringUtils.isEmpty.Colle

  • SpringBoot自动配置原理详解

    目录 阅读收获 一.SpringBoot是什么 二.SpringBoot的特点 三.启动类 3.1 @SpringBootApplication 四.@EnableAutoConfiguration 4.1 @AutoConfigurationPackage 4.2  @Import({AutoConfigurationImportSelector.class}) 五.流程总结图 六.常用的Conditional注解 七.@Import支持导入的三种方式 阅读收获 理解SpringBoot自动配

  • springboot整合mybatis流程详解

    目录 1.mybatis是什么 2.整合 2.1 导入依赖 2.2 创建包和类 2.3 在application.yaml配置mybatis 3.使用注解版mybaits 4.实战过程 1.mybatis是什么 MyBatis 是一款优秀的持久层框架,它支持自定义 SQL.存储过程以及高级映射.MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作.MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型.接口和 Java POJO(Plain Old Java

随机推荐