Spring Boot-自定义banner

发布于:2024-09-19 ⋅ 阅读:(135) ⋅ 点赞:(0)

在 Spring Boot 应用中,你可以自定义启动时显示的 banner。这些 banner 可以包括图形、文字或者其他形式的标识。如图所示:

1. 使用 banner.txt 文件

默认情况下,Spring Boot 使用项目的 banner.txt 文件中的内容作为启动时的 banner。你可以在 src/main/resources 目录下创建一个名为 banner.txt 的文件,并在其中放入自定义的 ASCII 艺术或文本。

例如在banner.txt文件中输入自定义文本:

  ____  _               _      
 / ___|| |_   ___  __ _| | ___ 
 \___ \| | | | \ \/ /| |/ _ \
  ___) | | |_| |>  < | |  __/
 |____/|_|\__,_/_/\_\|_|\___|
                             

重新运行Springboot项目即可。

2. 使用 Spring Boot Banner 类

如果你需要更高级的自定义,例如动态生成 banner 或从外部源加载,可以通过编写一个自定义 Banner 类来实现。实现 org.springframework.boot.Banner 接口,并重写 printBanner 方法

示例:

import org.springframework.boot.Banner;
import org.springframework.core.env.Environment;

import java.io.PrintStream;

public class CustomBanner implements Banner {

    @Override
    public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
        out.println("Custom Banner: Welcome to My Spring Boot Application!");
    }
}

然后,在 application.properties 文件中或在 SpringApplication 实例中配置自定义 banner:

application.properties 文件中配置:

spring.banner.location=classpath:custom-banner.txt

在你的 Spring Boot 主类中,你可以配置应用以使用自定义 Banner。例如:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setBanner(new CustomBanner()); // 设置自定义的 Banner
        app.run(args);
    }
}


 


网站公告

今日签到

点亮在社区的每一天
去签到