Spring Boot Banner打印:【从零开始学Spring Boot】-6.Spring Boot Banner自定义
1.banner 是如何打印的?
banner 是如何打印的呢?
在 spring boot 项目启动时,调用 run 方法,最终会调用到 printBanner 方法
public ConfigurableApplicationContext run(String... args) {
// ...
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
// 打印 banner
Banner printedBanner = printBanner(environment);
// ...
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
//...
return context;
}
它的实现如下
private Banner printBanner(ConfigurableEnvironment environment) {
// 如果关闭 banner,直接返回
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
// 默认 resourceLoader=null,使用 DefaultResourceLoader
ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
: new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
// bannerMode 有3中取值,OFF、CONSOLE、LOG,这里默认为 CONSOLE
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
// 打印 banner
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
bannerPrinter.print
Banner print(Environment environment, Class<?> sourceClass, PrintStream out) {
// 获取 banner,先获获取图片类型,再获取文本类型,都没有则答应 Spring Boot
Banner banner = getBanner(environment);
// 如果有多种类型,循环打印;按照添加顺序,先图片再文本
banner.printBanner(environment, sourceClass, out);
return new PrintedBanner(banner, sourceClass);
}
banner.printBanner
@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
for (Banner banner : this.banners) {
banner.printBanner(environment, sourceClass, out);
}
}
这里进行文本打印,ResourceBanner.printBanner
@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
try {
// 获取编码格式
String banner = StreamUtils.copyToString(this.resource.getInputStream(),
environment.getProperty("spring.banner.charset", Charset.class, StandardCharsets.UTF_8));
// 处理 banner 文件中属性值
for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) {
banner = resolver.resolvePlaceholders(banner);
}
// 使用 java bio 进行打印
out.println(banner);
}
catch (Exception ex) {
logger.warn(
"Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')",
ex);
}
}