起始
每次打开Spring Boot的应用的main方法时,都会出现下面如下所示Spring的Logo。

之前没有注意过这个Logo的配置,直到看到一个Spring Cloud的开源示例项目时,看到了一个配置如下:

有一个问题:为什么放在classpath下且名字为banner.txt就能够配置成功?
源码中的配置
入口
1 2 3
| public static void main(String[] args) { SpringApplication.run(CustomerStarter.class, args); }
|
最终执行的逻辑为:public ConfigurableApplicationContext run(String... args)
这个方法, 如下所示:

首先是设置不同的打印Logo的模式,模式包括日志、标准输出、关闭三种。

获取banner的步骤来了
1 2 3 4 5 6 7 8 9 10
| public Banner print(Environment environment, Class<?> sourceClass, Log logger) { Banner banner = getBanner(environment); try { logger.info(createStringFromBanner(banner, environment, sourceClass)); } catch (UnsupportedEncodingException ex) { logger.warn("Failed to create String for banner", ex); } return new PrintedBanner(banner, sourceClass); }
|
实际的获取都是在getBanner()这个方法里面,如下:
1 2 3 4 5 6 7 8 9 10 11 12
| private Banner getBanner(Environment environment) { Banners banners = new Banners(); banners.addIfNotNull(getImageBanner(environment)); banners.addIfNotNull(getTextBanner(environment)); if (banners.hasAtLeastOneBanner()) { return banners; } if (this.fallbackBanner != null) { return this.fallbackBanner; } return DEFAULT_BANNER; }
|
由上可知,存在两种banner,一种是文字类型的,一种是图片类型的。这两个banner都会被加载到banners中。获取文字和图片banner的源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| private Banner getImageBanner(Environment environment) { String location = environment.getProperty(BANNER_IMAGE_LOCATION_PROPERTY); if (StringUtils.hasLength(location)) { Resource resource = this.resourceLoader.getResource(location); return resource.exists() ? new ImageBanner(resource) : null; } for (String ext : IMAGE_EXTENSION) { Resource resource = this.resourceLoader.getResource("banner." + ext); if (resource.exists()) { return new ImageBanner(resource); } } return null; }
private Banner getTextBanner(Environment environment) { String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION); Resource resource = this.resourceLoader.getResource(location); if (resource.exists()) { return new ResourceBanner(resource); } return null; }
|
其中environment.getProperty()有两个参数,第一个是配置在yaml中的路径,第二个就是默认值,分别为:
1 2 3
| static final String BANNER_LOCATION_PROPERTY = "spring.banner.location"; static final String BANNER_IMAGE_LOCATION_PROPERTY = "spring.banner.image.location"; static final String DEFAULT_BANNER_LOCATION = "banner.txt";
|
至此,分析完毕。
这里还有一个问题,如何进行配置不同的打印方式?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public void setBannerMode(Banner.Mode bannerMode) { this.bannerMode = bannerMode; }
public SpringApplicationBuilder bannerMode(Banner.Mode bannerMode) { this.application.setBannerMode(bannerMode); return this; }
public static void main(String[] args) { SpringApplicationBuilder builder = new SpringApplicationBuilder(CustomerStarter.class); builder.bannerMode(Banner.Mode.OFF); builder.build(args).run(args); }
|
配置效果如下图所示:
