使用的 Spring Boot 3 的 SpringApplicationRunListener 实现自定义 Banner Starter 启动器

Spring boot 启动监听器 SpringApplicationRunListener、ApplicationRunner、CommandLineRunner 目录 SpringApplicationRunListener 概述 SpringApplicationRunListener 使用 SpringApplicationRunListener 概述 1、org.springframework.boot.SpringApplicationRunListener 监听器用于监听Spring Boot 启动过程中的不同时刻,从而可以加入自己的业务代码。 2、SpringApplicationRunListener 源码如下,方法执行的优先级从上到下是由. 阅读详情

以下是一个完整、标准、可直接使用的 Spring Boot 3 自定义 Banner Starter 实现方案,基于 SpringApplicationRunListener 实现,在应用启动最早期(日志输出前)替换默认 Banner,并支持通过 application.yaml 动态配置 Banner 内容。


✅ 项目目标

开发一个名为 custom-banner-starter 的 Spring Boot Starter,实现:

  • 自动替换 Spring Boot 默认 Banner;
  • Banner 内容可通过 application.yaml 配置;
  • 启动时机与官方一致:在日志输出前第一个打印;
  • 无需手动注册,通过 spring.factories 自动加载;
  • 支持 Spring Boot 3.x(兼容 Java 17+);

📁 项目结构

spring-boot-custom-banner-starter/
├── src/
│   └── main/
│       ├── java/
│       │   └── com/example/banner/
│       │       ├── CustomBanner.java                 # 自定义 Banner 实现
│       │       ├── CustomBannerAutoConfiguration.java # 自动配置类(可选,用于配置绑定)
│       │       └── CustomBannerProperties.java       # 配置属性类
│       └── resources/
│           ├── META-INF/
│           │   ├── spring.factories	# ✅ SPI 注册文件
│           │   └── spring/
│           │       └── org.springframework.boot.autoconfigure.AutoConfiguration.imports  # ✅ 自动配置注册(仅用于绑定配置)
│           └── application.yml.example               # 配置示例
└── pom.xml

🔧 1. CustomBannerProperties.java —— 配置属性类

package com.example.custombanner;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 自定义 Banner 配置属性类
 * 通过 application.yaml 配置,支持动态定制 Banner 内容
 * 前缀:custom.banner
 */
@Setter
@Getter 
@ConfigurationProperties(prefix = CustomBannerProperties.PREFIX)
public class CustomBannerProperties {
	public static final String PREFIX = "custom.banner";

    // 是否启用自定义 Banner(默认 true)
    private boolean enabled = true;

    // 默认标题(可覆盖)
    private String applicationName = "CUSTOM SPRING BOOT";

    // 项目版本号(默认使用 pom.xml 中的版本,也可自定义)
    private String version = "1.0.0";
    
    // 项目作者
    private String author;
    
    // 项目描述,默认取 pom.xml 中的 description
    private String description;
    
    // 是否显示系统信息   
    private boolean showSystemInfo = true;

    // 是否显示版本信息(默认 true)
    private boolean showVersion = true;

    // 输出类型
    private BannerType type = BannerType.TEXT;
    
    @Getter
    @RequiredArgsConstructor
    public enum BannerType {
        TEXT("text", "Text banner"),
        FIGLET("figlet", "Figlet banner"),
        IMAGE("image", "Image banner");

        private final String value;
        private final String description;
    }
}

✅ 说明:使用 @ConfigurationProperties 绑定 custom.banner.* 配置项,支持默认值和动态覆盖。


🔧 2. CustomSpringApplicationRunListener.java —— 核心监听器

package com.example.custombanner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Properties;

/**
 * 自定义 SpringApplicationRunListener,用于在 Spring Boot 启动最初始阶段(日志输出前)替换 Banner
 * 该监听器会在 SpringApplication.run() 调用时,由 Spring Boot 自动发现并执行
 * 优先级高于默认 Banner,确保在任何日志输出之前打印自定义内容
 */
package com.example.banner.listener;

import com.example.banner.printer.FigletBannerPrinter;
import com.example.banner.printer.ImageBannerPrinter;
import com.example.banner.printer.TextBannerPrinter;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.time.Duration;
import java.time.Instant;

/**
 * 自定义 SpringApplicationRunListener,用于在 Spring Boot 启动最初始阶段(日志输出前)替换 Banner
 * 该监听器会在 SpringApplication.run() 调用时,由 Spring Boot 自动发现并执行
 * 优先级高于默认 Banner,确保在任何日志输出之前打印自定义内容
 */
// 可参考 Spring Boot 官方的示例类 EventPublishingRunListener
public class CustomSpringApplicationRunListener implements SpringApplicationRunListener, Ordered {
    private final SpringApplication application;
    private final String[] args;
    private Instant startTime;
    private Instant contextPreparedTime;

    /**
     * 必须的构造函数
     * Spring Boot 会通过反射调用这个构造函数
     */
    public CustomSpringApplicationRunListener(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
        System.out.println("CustomSpringApplicationRunListener 构造函数被调用");
    }
    
    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        startTime = Instant.now();
        System.out.println("🚀 [阶段1 - starting] 应用启动开始");
        System.out.println("   启动时间: " + startTime);
        System.out.println("   主应用类: " + application.getMainApplicationClass());
        System.out.println("   命令行参数: " + String.join(", ", args));
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("🌍 [阶段2 - environmentPrepared] 环境准备完成");
        System.out.println("   激活的配置文件: " + String.join(", ", environment.getActiveProfiles()));
        System.out.println("   默认配置文件: " + String.join(", ", environment.getDefaultProfiles()));
        System.out.println("   应用名称: " + environment.getProperty("spring.application.name", "未设置"));
        switch (environment.getProperty("custom.banner.type", "figlet")) {
            case "text":
                new TextBannerPrinter().printBanner(environment, application.getMainApplicationClass(), System.out);
                break;
            case "figlet":
                new FigletBannerPrinter().printBanner(environment, application.getMainApplicationClass(), System.out);
                break;
            case "image":
                new ImageBannerPrinter().printBanner(environment, application.getMainApplicationClass(), System.out);
                break;
        }

    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        contextPreparedTime = Instant.now();
        System.out.println("🔧 [阶段3 - contextPrepared] 应用上下文创建完成");
        System.out.println("   上下文ID: " + context.getId());
        System.out.println("   上下文显示名称: " + context.getDisplayName());
        System.out.println("   启动阶段耗时: " +
                Duration.between(startTime, contextPreparedTime).toMillis() + "ms");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        Instant contextLoadedTime = Instant.now();
        System.out.println("📦 [阶段4 - contextLoaded] Bean定义加载完成");
        System.out.println("   Bean定义数量: " + context.getBeanDefinitionCount());
        System.out.println("   上下文准备耗时: " +
                Duration.between(contextPreparedTime, contextLoadedTime).toMillis() + "ms");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("✅ [阶段5 - started] 应用上下文刷新完成");
        System.out.println("   启动总耗时: " + timeTaken.toMillis() + "ms");
        System.out.println("   所有Bean定义: " + String.join(", ", context.getBeanDefinitionNames()));
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("🎉 [阶段6 - ready] 应用完全启动完成");
        System.out.println("   就绪阶段耗时: " + timeTaken.toMillis() + "ms");
        System.out.println("   总启动时间: " +
                Duration.between(startTime, Instant.now()).toMillis() + "ms");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        SpringApplicationRunListener.super.failed(context, exception);
        System.out.println("❌ [阶段7 - failed] 应用启动失败");
        System.out.println("   失败原因: " + exception.getMessage());
        System.out.println("   失败时间: " + Instant.now());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

✅ 关键点说明:

  • starting() 方法是唯一能在日志输出前打印 Banner 的时机;
  • environmentPrepared() 用于提前读取配置,因为此时 ApplicationContext 还未创建,不能使用 @Autowired;
  • 使用 System.out.println() 直接输出,确保在日志框架(Logback)初始化前完成;
  • 配置绑定通过 Properties 手动解析,兼容 Spring Boot 3 的启动顺序。

🔧 3. CustomBannerAutoConfiguration.java —— 自动配置类

package com.example.custombanner;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 自动配置类:启用自定义 Banner Starter
 * 该类仅用于注册 @ConfigurationProperties 和确保监听器被加载
 * 实际的监听器注册通过 META-INF/spring.factories 完成
 */
@Configuration
@EnableConfigurationProperties(CustomBannerProperties.class)
@ConditionalOnProperty(
    prefix = "custom.banner",
    name = "enabled",
    havingValue = "true",
    matchIfMissing = true // 默认启用
)
public class CustomBannerAutoConfiguration {
    // 此类无需任何 Bean 定义,仅用于激活配置绑定
    // 真正的监听器注册在 spring.factories 中
}

✅ 说明:此配置类确保 @ConfigurationProperties 生效,并通过 @ConditionalOnProperty 控制是否启用(默认开启)。


📦 4. META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports —— Spring Boot 3 注册 IOC 组件的新方式

✅ 这是 Spring Boot 3 的新的 IOC 组件注册机制,替代旧版 spring.factories 但是 SpringApplicationRunListener 监听器的注册依旧依赖于 spring.factories 来完成,这一点需要特别注意

在 src/main/resources/META-INF/ 目录下创建 spring.factories 文件:

# src/main/resources/META-INF/spring.factories
org.springframework.boot.SpringApplicationRunListener=\
    com.example.banner.listener.CustomSpringApplicationRunListener

在 src/main/resources/META-INF/spring/ 目录下创建 org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件:

# src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.example.banner.CustomBannerAutoConfiguration

艺术字输出工具类:

package com.example.banner.utils;

import lombok.Getter;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;

/**
 * Figlet 艺术字体工具类
 * 用于将普通文本转换为ASCII艺术字体
 * <p>
 * Figlet 是一种将普通文本转换为大型字母的程序,
 * 字母由文本字符组成,类似于早期电脑和游戏机上的字符艺术。</p>
 *
 * @author urbane
 * @since 1.0.0
 */
@Getter
public class FigletUtil {

    /**
     * 支持的最大字符数
     */
    private static final int MAX_CHARS = 1024;
    /**
     * 硬空格字符,用于替换普通空格
     */
    private final char hardBlank;
    /**
     * 字体高度(行数)
     */
    private final int height;
    /**
     * 不包含下降部分的字体高度
     */
    private final int heightWithoutDescenders;
    /**
     * 最大行长度
     */
    private final int maxLine;
    /**
     * 字符压缩模式
     */
    private final int smushMode;
    /**
     * 字体数据数组
     * 三维数组:[字符编码][行数][列数]
     */
    private final char[][][] font; // [charCode][row][col]
    /**
     * 字体名称
     */
    private final String fontName;

    /**
     * 构造函数,从输入流加载字体文件
     *
     * @param fontStream 字体文件输入流
     * @throws IOException 当读取字体文件出错时抛出
     */
    public FigletUtil(InputStream fontStream) throws IOException {
        if (fontStream == null) {
            throw new IllegalArgumentException("Font stream cannot be null");
        }

        this.font = new char[MAX_CHARS][][];

        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(new BufferedInputStream(fontStream), StandardCharsets.UTF_8))) {

            // 读取字体文件头部信息
            String headerLine = bufferedReader.readLine();
            if (headerLine == null) {
                throw new IOException("Invalid font file: empty header");
            }
            StringTokenizer tokenizer = new StringTokenizer(headerLine, " ");
            if (tokenizer.countTokens() < 6) {
                throw new IOException("Invalid font header format");
            }

            // 解析字体基本信息
            String signature = tokenizer.nextToken();
            this.hardBlank = signature.charAt(signature.length() - 1);
            this.height = Integer.parseInt(tokenizer.nextToken());
            this.heightWithoutDescenders = Integer.parseInt(tokenizer.nextToken());
            this.maxLine = Integer.parseInt(tokenizer.nextToken());
            this.smushMode = Integer.parseInt(tokenizer.nextToken());

            // 读取注释行数
            int commentLines = Integer.parseInt(tokenizer.nextToken());

            // 读取字体名称
            tokenizer = new StringTokenizer(bufferedReader.readLine(), " ");
            if (tokenizer.hasMoreElements()) {
                this.fontName = tokenizer.nextToken();
            } else {
                this.fontName = "";
            }

            // 跳过注释行
            for (int i = 0; i < commentLines - 1; i++) {
                bufferedReader.readLine();
            }

            // 读取字符数据
            int charCode = 31;
            while (headerLine != null) {
                ++charCode;

                for (int lineIndex = 0; lineIndex < this.height; ++lineIndex) {
                    headerLine = bufferedReader.readLine();
                    if (headerLine != null) {
                        boolean isAbnormalFormat = true;
                        if (lineIndex == 0) {
                            try {
                                String codeTag = headerLine.concat(" ").split(" ")[0];
                                if (codeTag.length() > 2 && "x".equals(codeTag.substring(1, 2))) {
                                    // 十六进制编码
                                    charCode = Integer.parseInt(codeTag.substring(2), 16);
                                } else {
                                    // 十进制编码
                                    charCode = Integer.parseInt(codeTag);
                                }
                            } catch (NumberFormatException var18) {
                                isAbnormalFormat = false;
                            }
                            // 如果是异常格式,读取下一行并恢复字符编码
                            if (isAbnormalFormat) {
                                headerLine = bufferedReader.readLine();
                            }
                        }

                        // 初始化字符数据数组
                        if (lineIndex == 0) {
                            this.font[charCode] = new char[this.height][];
                        }

                        // 计算当前行的有效长度
                        int effectiveLength = headerLine.length() - 1 - (lineIndex == this.height - 1 ? 1 : 0);
                        if (this.height == 1) {
                            ++effectiveLength;
                        }

                        // 分配数组空间
                        this.font[charCode][lineIndex] = new char[effectiveLength];

                        // 处理字符数据,将硬空格替换为空格
                        // 处理字符数据,将硬空格替换为空格
                        for (int charIndex = 0; charIndex < effectiveLength; charIndex++) {
                            char currentChar = headerLine.charAt(charIndex);
                            this.font[charCode][lineIndex][charIndex] =
                                    (currentChar == this.hardBlank) ? ' ' : currentChar;
                        }
                    }
                }
            }
        }
    }

    /**
     * 将普通文本转换为 Figlet 艺术字体
     *
     * @param message 要转换的文本
     * @return 转换后的艺术字体字符串
     */
    public String convert(String message) {
        StringBuilder result = new StringBuilder();

        // 按行处理,逐行构建艺术字体
        for (int lineIndex = 0; lineIndex < this.height; lineIndex++) {
            // 处理每个字符
            for (int charIndex = 0; charIndex < message.length(); charIndex++) {
                String charLine = this.getCharLineString(message.charAt(charIndex), lineIndex);
                if (charLine != null) {
                    result.append(charLine);
                }
            }
            // 每行结束后添加换行符
            result.append('\n');
        }

        return result.toString();
    }

    /**
     * 获取指定字符某一行的字符串表示
     *
     * @param characterCode 字符的ASCII码
     * @param lineIndex     行索引
     * @return 指定行的字符串,如果不存在则返回null
     */
    public String getCharLineString(int characterCode, int lineIndex) {
        return this.font[characterCode][lineIndex] == null ? null : new String(this.font[characterCode][lineIndex]);
    }

    /**
     * 使用默认字体(Standard.flf)转换单行文本
     *
     * @param message 要转换的文本
     * @return 转换后的艺术字体字符串
     * @throws IOException 当读取字体文件或转换过程中出错时抛出
     */
    public static String convertOneLine(String message) throws IOException {
        return convertOneLine(FigletUtil.class.getClassLoader().getResourceAsStream("/fonts/Standard.flf"), message);
    }

    /**
     * 使用指定字体流转换单行文本
     *
     * @param fontFileStream 字体文件输入流
     * @param message        要转换的文本
     * @return 转换后的艺术字体字符串
     * @throws IOException 当读取字体文件或转换过程中出错时抛出
     */
    public static String convertOneLine(InputStream fontFileStream, String message) throws IOException {
        return (new FigletUtil(fontFileStream)).convert(message);
    }

    /**
     * 使用指定字体文件转换单行文本
     *
     * @param fontFile 字体文件
     * @param message  要转换的文本
     * @return 转换后的艺术字体字符串
     * @throws IOException 当读取字体文件或转换过程中出错时抛出
     */
    public static String convertOneLine(File fontFile, String message) throws IOException {
        return convertOneLine(new FileInputStream(fontFile), message);
    }
}

package com.example.banner.printer;

import com.example.banner.utils.FigletUtil;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringBootVersion;
import org.springframework.core.env.Environment;

import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FigletBannerPrinter implements Banner {

    private static final String RESET = "\u001B[0m";
    private static final String GREEN = "\u001B[32m";
    private static final String CYAN = "\u001B[36m";
    private static final String YELLOW = "\u001B[33m";

    @Override
    public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
        try {
            // 获取服务名(动态!)
            String appName = environment.getProperty("spring.application.name", "Unknown-Service").toUpperCase();

            // ✅ 动态生成 ASCII Art 标题
            String asciiArtTitle = generateAsciiArt(appName);

            // 其他信息
            String serverPort = environment.getProperty("server.port", "8080");
            String profiles = String.join(",", environment.getActiveProfiles());
            String version = environment.getProperty("info.app.version", "1.0.0");
            String springBootVersion = SpringBootVersion.getVersion();
            String startTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String author = environment.getProperty("custom.banner.author", "unknown");
            String hostAddress = getHostAddress();
            String baseUrl = "https://" + hostAddress + ":" + serverPort;
            String healthUrl = baseUrl + "/actuator/health";
            String swaggerUrl = baseUrl + (isSwaggerV3(environment) ? "/swagger-ui/index.html" : "/swagger-ui.html");

            // 打印横幅
            out.println(GREEN + "===============================================" + RESET);
            out.println(CYAN + asciiArtTitle + RESET); // ✅ 动态 ASCII Art 标题
            out.println(GREEN + "===============================================" + RESET);
            out.println("  服务端口    : " + YELLOW + "🌐 " + serverPort + RESET);
            out.println("  服务IP      : " + CYAN + "📍 " + hostAddress + RESET);
            out.println("  激活环境    : " + GREEN + "🧪 " + (profiles.isEmpty() ? "default" : profiles) + RESET);
            out.println("  服务版本    : " + YELLOW + "🏷️  " + version + RESET);
            out.println("  Spring Boot : " + GREEN + "🌱 " + springBootVersion + RESET);
            out.println("  启动时间    : " + YELLOW + "🕙 " + startTime + RESET);
            out.println("  项目作者    : " + CYAN + "📍 " + author + RESET);
            out.println("  健康检查    : " + CYAN + "🩺 " + healthUrl + RESET);
            out.println("  Swagger文档 : " + GREEN + "📚 " + swaggerUrl + RESET);
            out.println(GREEN + "===============================================" + RESET);
        } catch (Exception e) {
            out.println("⚠️  横幅打印异常: " + e.getMessage());
        }
    }

    // ✅ 核心方法:动态生成 ASCII Art
    private String generateAsciiArt(String text) {
        try {
            // 可选的字体文件下载,参考官网 https://github.com/xero/figlet-fonts/tree/master
            // 或者直接去 ASCII 艺术字生成工具推荐:https://patorjk.com/software/taag/#p=testall 去在线挑选

            // figlet 内置字体 "slant"(推荐),也可换 "standard",
            // return FigletFont.convertOneLine(text); // 默认 slant
            // return FigletFont.convertOneLine(text, "standard");

            // 自定义字体,figlet 工具包默认只提供了两个字体,我不喜欢。可以到 https://github.com/xero/figlet-fonts/tree/master 选择自己喜欢的字体
            InputStream fontStream = getClass().getResourceAsStream("/fonts/ANSI Shadow.flf");
//             InputStream fontStream = getClass().getResourceAsStream("/fonts/ANSI Regular.flf");

            // 使用内置字体 "slant", "standard"(默认) 两种可选字体,也可以下载并使用自定义字体
            return FigletUtil.convertOneLine(fontStream, text);
        } catch (Exception e) {
            // 降级:如果字体转换失败,返回原始文本
            return "🚀 " + text;
        }
    }

    // 判断是否 Swagger V3
    private boolean isSwaggerV3(Environment environment) {
        return environment.getProperty("springdoc.api-docs.enabled", Boolean.class, false) ||
                environment.containsProperty("springdoc.swagger-ui.path");
    }

    // 获取主机 IP
    private String getHostAddress() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                return String.valueOf(InetAddress.getByName(java.net.NetworkInterface
                        .getNetworkInterfaces().nextElement().getInetAddresses().nextElement().getHostAddress()));
            }
            return address.getHostAddress();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }
}

📄 5. 可选:提供示例配置文件 application.yml.example

在 src/main/resources/ 下创建:

# custom-banner-starter 示例配置
# 请复制到你的 application.yaml 中并按需修改

custom:
  banner:
    enabled: true                  # 是否启用自定义 Banner(默认 true)
    title: "MY INSURANCE SYSTEM"   # 自定义标题(默认:CUSTOM SPRING BOOT)
    version: "v1.0.0-INSURANCE"    # 自定义版本(默认:自动获取 Spring Boot 版本)
    border-char: "="               # 边框字符(默认:=)
    show-spring-logo: true         # 是否显示 Spring 徽标(默认 true)
    show-version: true             # 是否显示版本(默认 true)

✅ 用户只需将此内容复制到自己的 application.yaml 中即可定制。


📦 6. pom.xml(Maven 依赖)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>custom-banner-starter</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>custom-banner-starter</name>
    <description>自定义 Spring Boot Banner 启动器</description>

    <properties>
        <java.version>17</java.version>
        <spring-boot.version>3.5.4</spring-boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <skip>true</skip> <!-- 此 starter 不需打包为可执行 jar -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

✅ 7. 使用示例(在目标 Spring Boot 项目中)

① 引入依赖(Maven)

<dependency>
    <groupId>com.example</groupId>
    <artifactId>custom-banner-starter</artifactId>
    <version>1.0.0</version>
</dependency>

② 在 application.yaml 中配置(可选)

custom:
  banner:
    title: "人寿保险核心系统"
    version: "v2.3.1-PROD"
    border-char: "#"
    show-spring-logo: false
    show-version: true

③ 启动应用,效果如下:

============================================================
 :: 人寿保险核心系统 ::
v2.3.1-PROD
============================================================

✅ 在任何日志输出之前打印,完全替代默认 Banner。


🔍 8. 与 ApplicationListener / CommandLineRunner 的区别

特性SpringApplicationRunListenerApplicationListener<ContextRefreshedEvent>CommandLineRunner / ApplicationRunner
执行时机最早(日志前)上下文刷新后(应用已启动)应用启动完成后
能否改 Banner✅ 唯一正确方式❌ 太晚,日志已输出❌ 太晚
是否需要手动注册❌ 自动发现(通过 imports)✅ 需要 @Component✅ 需要 @Component
是否影响启动流程✅ 影响启动早期阶段❌ 仅在启动后触发❌ 启动后触发

✅ 结论:只有 SpringApplicationRunListener 能在日志输出前修改 Banner,是唯一合法方案。


⚠️ 9. 注意事项与最佳实践

项目说明
文件命名必须精确META-INF/spring/org.springframework.boot.SpringApplicationRunListener 必须完全匹配,大小写敏感
不要使用 @ComponentCustomSpringApplicationRunListener 不要加 @Component,否则会被重复加载
避免使用 Spring Bean在 starting() 中不能注入 @Autowired Bean,因为上下文尚未初始化
使用 System.out.println必须使用原生输出,避免 Logger,否则可能被日志框架拦截或延迟
配置优先级custom.banner.enabled=false 可关闭此 Starter,不影响其他功能
兼容性本方案兼容 Spring Boot 3.0+,不支持 2.x(因注册机制不同)
测试建议在独立 Spring Boot 项目中测试,避免与已有 Banner 冲突

✅ 10. 总结:为什么这个方案是“标准”的?

优势说明
✅ 时机精准使用 SpringApplicationRunListener.starting(),确保 Banner 在日志前输出
✅ 配置灵活支持通过 application.yaml 动态定制,无需重新打包
✅ 自动注册使用 Spring Boot 3 推荐的 AutoConfiguration.imports,无 spring.factories 兼容问题
✅ 无侵入性不修改用户代码,引入即生效
✅ 企业级可用适合银行、保险等对启动信息有品牌要求的场景
✅ 符合规范严格遵循 Spring Boot 官方扩展机制

📎 附:如何发布到私有仓库?

  1. 执行 mvn clean install → 本地仓库;
  2. 或部署到公司 Nexus/Artifactory;
  3. 项目中引入依赖即可自动生效。

✅ 最终效果:你的保险系统启动时,不再显示“Spring Boot :: (v3.5.4)”,而是优雅地展示 “人寿保险核心系统 v2.3.1-PROD”,体现专业性和品牌一致性。

利用OTSU阈值算法在ZYNQ上实现浒苔识别 利用OTSU阈值算法进行图像二值化,结果用HDMI显示 阅读详情

相关推荐

智能座舱架构与芯片- (9) 音频篇 上

从A2B收发器衍生出来的简化产品具备各种级别的功能,例如端点从节点(不支持TDM)、简化型主节点(支持较短的电缆和更少的从节点数量),以及简化型端点从节点(支持较短电缆和更少的PDM输入)。例如,AVB中的talker和listener是不同的设备,它们的参考时钟源可能并不相同。传统的车载收音机通过天线接收无线电信号,然后由调谐模块(Tuner)进行信号调谐,信道过滤,信道均衡,多路改善,信号解调等,转为数字信号后再交给DSP进行立体声解码,噪声抑制,弱信号处理,最后从车载音响系统进行播放。

joanna_xiao的博客 4922

【Spring Boot】自定义 Banner

启动 Spring Boot 时,几乎总是能在控制台上方看到如下横幅,这个也叫字符画、英文ASCII艺术字。

Hi there 6429

记录一次小项目中的重放攻击与解决方案

文章目录1、重放攻击简介2、重放攻击演示3、解决方案4、重放攻击验证 欢迎各位 前(提)来(出)讨(意)论(见)。 1、重放攻击简介 重放攻击(Replay Attacks)又称重播攻击、回放攻击,是指攻击者发送一个目的主机已接收过的包,来达到欺骗系统的目的,主要用于身份认证过程,破坏认证的正确性。 举个简单的小例子。 我们往系统里面插入一条数据,如果此次操作的数据包被攻击者获取,又恰巧后台没有对重复内容进行验证,那么攻击者就可以利用该数据包重复的发起请求,无限制的往数据库插入数据,即使请求包是加密的也

fiveSix 8732

Java --- springboot3自定义banner与SpringApplication

Spring Boot banner在线生成工具,制作下载英文banner.txt,修改替换banner.txt文字实现自定义,个性化启动banner-bootschool.net修改springboot的配置文件#修改为自己定义的banner#banner的模式测试结果://SpringApplication:springboot应用的核心API入口//自定义SpringApplication的底层设置//设置banner,如果配置文件配置了以配置文件优先//运行程序。

qq_46093575的博客 1704

【SPI-NAND】Linux驱动移植实战:从规格书解析到内核适配

本文详细解析了SPI-NAND Flash的Linux驱动移植实战,从规格书关键参数提取到内核MTD子系统适配。内容涵盖存储结构解析、命令集映射、设备树配置及厂商驱动开发,特别强调ECC校验、坏块管理等NAND特性处理,并提供了性能优化与测试验证的实用技巧。

weixin_27076351的博客 355

基于大模型的肾结石诊疗全流程风险预测与方案制定研究报告

目录一、引言1.1 研究背景与意义1.2 国内外研究现状1.3 研究目标与内容二、大模型技术原理与应用概述2.1 大模型的基本原理2.2 大模型在医疗领域的应用进展2.3 适用于肾结石预测的大模型选择与依据三、术前风险预测与准备3.1 患者身体状况评估3.2 结石情况分析3.3 术前准备方案制定四、术中风险预测与应对4.1 出血风险预测与处理4.2 脏器损伤风险预测与预防4.3 实时监测与决策支持五、术后恢复预测与护理5.1 恢复时间预测5.2 护理要点与措施5.3 并发症预防与处理六、并发症风险预测与管理

嵌入式毕设/课设资料清单(速查手册·文档模板·题库,持续更新)→ 见最新文章 1151

SpringBoot3—核心特性:基础特性

SpringBoot3—核心特性:基础特性

weixin_74019079的博客 1127

使用在UE5中使用AirSim插件Eigen库头文件引用报错,出现报错的解决方式

如图所示,用红线圈出的两条头文件引用会报错,提示无法找到他们,但是可以发现的是,他们的路径书写是没有问题的。在终端中运行时候,会出现如下的报错。

GFCLJY的博客 1009

Java程序设计:spring boot(3)——spring boot核心配置

Spring Boot 项⽬启动时默认加载 src/main/resources ⽬录下的 banner.txt 图标⽂件,如果该⽬录 ⽂件未提供,则使⽤ Spring Boot 默认。在 main ⽬录下新建 resources 资源⽬录,并在该⽬录下新建 banner.txt ⽂本⽂件,可以设置⾃定义图标。打开⽹址: http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something。

茜茜西西的博客 1640

顶刊《会计研究》数据复现|最新上市公司数智化数据

本文基于Python文本分析方法构建了中国A股上市公司数智化指标(1991-2024),通过识别年报中的"机器学习""智能医疗"等关键词,量化企业数字化与智能化融合程度。研究发现数智化企业更倾向于非正式渠道的定性披露以规避风险,该指标为监管完善信披规则提供了参考。研究还揭示了数智化对企业信息披露策略的转变,并提出了未来研究方向,包括数智化对绿色创新、ESG表现等影响机制。数据覆盖非金融类上市公司,采用文本挖掘技术构建结构化指标,为相关领域研究提供了微观基础。

PPdata_Academy的博客 1493

实战篇(七):使用Processing和PixelFlow库创建交互式流体太极动画

类:用于配置流体运动的参数,比如圆的位置、半径、运动的角度和速度以及颜色等。类:实现了接口,用于更新流体物理仿真的状态,同时整合声音输入作为流体动态变化的一部分。my_update方法:是流体物理仿真更新的核心,它计算流体粒子的速度和位置,并且将这些数据传递给流体库来模拟流动。现在,让我们进一步分析并解释每个部分的作用以及如何操作。float x;// 圆心位置xfloat y;// 圆心位置y// 半径// 是否是顺时针// 圆周运动,弧上的点位置,以及上一帧的点位置// 角度。

帅小柏的博客 1636

Spring Boot 3.0 (十八):Spring Boot 动态 Banner

Spring Boot 提供了很多新特性,其中就有一个小彩蛋:动态 Banner,今天我们就先拿这个来尝尝鲜。

qq_2118119173的博客 216

【Proteus仿真】AT89C51单片机中断系列仿真——INT0中断控制LED小灯/INT0和INT1中断控制数码管

本文介绍了基于51单片机外部中断(INT0/INT1)的四个实践案例:1)INT0控制LED开关;2)INT0中断实现数码管计数/清零;3)INT0中断构建秒表功能(启动/暂停/清零);4)INT0/INT1双中断独立控制两组数码管计数。每个案例包含电路原理图、接线说明及完整源代码,重点演示了外部中断在硬件控制中的应用方法。附加硬件工程师笔试面试资料链接,涵盖器件知识、Multisim教程等内容,适合嵌入式学习者参考实践。(149字)

XU157303764的博客 1917

SpringBoot 核心笔记

SpringBoot 是简化 Spring 开发的一站式框架,是整个 Spring 技术栈的整合。传统Spring开发需要大量XML配置,而SpringBoot通过自动配置、场景启动器starter,极大减少配置工作。微服务架构的流行也离不开SpringBoot作为基础开发框架。微服务(Martin Fowler,2014):将单体应用拆分为一组小型独立服务,服务之间通过HTTP通信;每个功能元素是可独立替换、独立升级的单元。单体应用:All In One,所有功能打包在一个应用中。日志实现。

estrusKing的博客 240

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

初探 SpringBoot 之自动配置

初探 SpringBoot 之自动配置

u012026406的博客 1678

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

SpringBoot3 基础特性

1.3. FluentBuilder API 2. Profiles 环境隔离能力;快速切换开发、测试、生产环境步骤: 2.1.1 指定环境 Spring Profiles 提供一种隔离配置的方式,使其仅在特定环境生效; 任何@Component, @Configuration 或 @ConfigurationProperties 可以使用 @Profile 标记,来指定何时被加载。【容器中的组件都可以被 标记】 @prifile是可以用在组件@Bean上的,表示此组件的生效环境,如果没有具体指定环境就

一位打工仔的博客 1178

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

SpringBoot3【④ 基础特性(外部和内部化配置,整合Junit)】

SpringBoot3【④ 基础特性(外部和内部化配置,整合Junit)】

weixin_44981126的博客 1064

springboot3--基础特性

1.类路径添加banner.txt或设置就可以定制 bannerspring.main.banner-mode=off //关闭2.推荐网站:Spring Boot banner 在线生成工具,制作下载英文 banner.txt,修改替换 banner.txt 文字实现自定义,个性化启动 banner-bootschool.net//SpringApplication:Boot应用的核心API入口//1.自定义SpringApplication的底层设置//配置以配置文件优先。

qq_44761778的博客 513

SpringBoot——Banner介绍

springboot的banner的介绍

Luffy的博客 9801

SpringBoot3基础特性

介绍了SpringBoot的一些基础特性。

xry12354的博客 433

springboot_3-启动控制台logo更换(banner配置)

更换这玩应 在resource目录下新建banner.txt文件 随便写内容 启动项目 ok

Smile__1的博客 3957

SpringBoot (四):自定义Banner

创建 banner.txt 文件:在 src/main/resources 目录下创建一个名为 banner.txt 的文件。

qq_63238915的博客 441

SpringBoot3-第四篇(基础特性)

类路径添加banner.txt或设置就可以定制 bannerSpring Boot banner 在线生成工具,制作下载英文 banner.txt,修改替换 banner.txt 文字实现自定义,个性化启动 banner-bootschool.net} }} }} }Banner;

moments的博客 1093

Spring Boot 3.0.0正式发布,Banner不再支持图片&增强可观测性

技术向前的大船,浩浩荡荡不可逆。作为技术人,我们能做的是keep moving,不管是技术架构师还是业务架构师,还是开发工程师!

架构师:通透,才能写出好代码! 3558

SpringBoot-03-修改Banner图

自定义修改程序启动过程当中的banner图

老姚 1840

SpringBoot3-核心原理

场景:抽取聊天机器人场景,它可以打招呼。效果:任何项目导入此starter都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改● 1. 创建自定义starter项目,引入spring-boot-starter基础依赖● 2. 编写模块功能,引入模块所有需要的依赖。● 3. 编写xxxAutoConfiguration自动配置类,帮其他项目导入这个模块需要的所有组件。

淼淼不暴躁! 400
上一篇: Spring Boot `SpringApplicationRunListener` 深度系统性学习与实战完整文档
下一篇: Spring Boot 3 中实现文件上传、下载以及 Excel 导入导出
龙茶清欢
博客等级 码龄7年 3720粉丝 375原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址