Banner 自定义规范

为什么要打印 Banner?

1. 品牌标识与框架认知

Banner 就像是框架的”身份证”,它在应用启动的第一时间向开发者宣告:”我来了!”

2. 实用价值:版本管理与问题排查

版本信息展示

在生产环境中,快速确认框架版本对于问题排查至关重要,可以通过日志快速定位版本信息

启动状态确认

Banner 的成功打印意味着框架的核心组件已经正确初始化

3. 社区建设与开源文化

通过 Banner 展示项目地址和官网链接

核心实现解析

patorjk.com 在线生成 Banner

ps:为什么版本信息为空,下述会讲到

版本信息处理

1
2
3
4
5
public OneThreadBannerHandler(BuildProperties buildProperties) {
this.version = buildProperties != null ? buildProperties.getVersion() : "";
}

String bannerVersion = StrUtil.isNotEmpty(version) ? " (v" + version + ")" : "no version.";

版本信息的获取策略:

  • 优先使用 BuildProperties:从 Maven/Gradle 构建信息中获取准确版本
  • 降级处理:如果无法获取版本信息,显示”no version.”
  • 格式统一:版本号统一格式为”(v1.0.3)

自动配置集成

YsyThreadBannerHandler 实现了InitializingBean接口,使用了初始化事件绑定,自然需要自动装配

1
2
3
4
5
6
7
8
public class YsyThreadBannerHandler implements InitializingBean{
// ......
}

@Bean
public YsyThreadBannerHandler ysyThreadBannerHandler(ObjectProvider<BuildProperties> buildProperties) {
return new YsyThreadBannerHandler(buildProperties.getIfAvailable());
}

为什么项目启动版本号显示 no version?

原因是 BuildProperties 没有成功注入,导致 version 为空

Spring BootBuildProperties 的来源是 spring-boot-maven-plugin 在打包时生成的 META-INF/build-info.properties 文件,它默认不会生成,得在common-spring-boot-starterpom.xml 里加上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<build>
   <plugins>
       <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
           <configuration>
               <layers>
                   <enabled>true</enabled>
               </layers>
           </configuration>
           <executions>
               <execution>
                   <goals>
                       <!-- 生成 build-info.properties -->
                       <goal>build-info</goal>
                   </goals>
               </execution>
           </executions>
       </plugin>
   </plugins>
</build>

这个 Maven 插件的生命周期绑定的是 compile 阶段,必须要执行下 compilepackage 或者 install 等才会有这个信息