Spring boot Banner和icon

本文介绍了如何在Spring Boot项目中自定义启动时的Banner和应用图标。内容包括创建`banner.txt`文件来定制文字Banner,通过设置`banner.mode`关闭Banner,使用图片作为Banner,以及在resources目录下添加`favicon.ico`来替换默认图标。同时,文章还简要分析了Spring Boot启动流程中的相关源码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring boot Banner和icon

上一节

上一节:Spring boot 基础web入门搭建

源码

源码链接地址

banner 和icon 就是做一些启动或者页面系统标识的作用;
首先创建一个web项目,如果不是很熟悉请参考上一节:Spring boot 基础web入门搭建 搭建

知识点

  1. 自定义banner 和icon
  2. 初识 springboot 启动流程

Spring boot banner

springboot 自带的banner

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

自定义banner
  1. 在resources 目录下创建banner.txt文件
  2. 制作banner
    banner 制作网站
  3. 修改banner.txt文件
${AnsiColor.BLUE}
${spring-boot.version}
${spring.application.name}
${info.name}
    _                             _         _
  /' )       _                   ( )       ( `\
/' /'       (_)   _ _    _      _| | _   _  `\ `\
<  <   (`\/')| | /'_` ) /'_`\  /'_` |( ) ( )   >  >
\  `\  >  < | |( (_| |( (_) )( (_| || (_) | /' /'
 `\__)(_/\_)(_)`\__,_)`\___/'`\__,_)`\___/'(_/'
 $可以获取配置文件中的信息,  ${AnsiColor.BLUE} 修改字体颜色   ${AnsiBackground.YELLOW}修改背景颜色

从新启动,日志打印

2.1.6.RELEASE
banner-demo
banner-icon-demo
     _                             _         _
   /' )       _                   ( )       ( `\
 /' /'       (_)   _ _    _      _| | _   _  `\ `\
<  <   (`\/')| | /'_` ) /'_`\  /'_` |( ) ( )   >  >
 \  `\  >  < | |( (_| |( (_) )( (_| || (_) | /' /'
  `\__)(_/\_)(_)`\__,_)`\___/'`\__,_)`\___/'(_/'
关闭banner

通过springapplication.setBannerMode 进行设置;banner.mode 有三种配置,off 关闭,console控制台,log 打印到日志;

  public static void main(String[] args) {

//        ConfigurableApplicationContext run = SpringApplication.run(ApplicationStart.class, args);
        SpringApplication springApplication = new SpringApplication();
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.addPrimarySources(Stream.of(ApplicationStart.class).collect(Collectors.toList()));
        springApplication.run(args);

    }
使用图片充当banner
resources 目录下创建banner.jpg,  默认支持 { "gif", "jpg", "png" } 这几种格式 
源码分析

启动入口 springApplication.run 方法 > pringtBanner(environment)

private Banner printBanner(ConfigurableEnvironment environment) {
		if (this.bannerMode == Banner.Mode.OFF) {
			return null;
		}
		ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
				: new DefaultResourceLoader(getClassLoader());
		// 使用SpringApplicationBannerPrinter 进行打印
		SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
		if (this.bannerMode == Mode.LOG) {
			return bannerPrinter.print(environment, this.mainApplicationClass, logger);
		}
		return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
	}

bannerPrinter.print

	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, 默认使用的是 SpringBootBanner

	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.printBanner(environment, sourceClass, out); 打印到控制台

Spring boot icon

在resources 目录下加入自己的favicon.ico 即可更改;springboot提供了这些静态资源路径都是可以的

{ “classpath:/META-INF/resources/”,“classpath:/resources/”, “classpath:/static/”, “classpath:/public/” }

源码分析

重要类: WebMvcAutoConfiguration
这里就提现了 springboot 自动装配的特点
在WebMvcAutoConfiguration中找到 FaviconConfiguration静态内部类

@Configuration
		@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
		public static class FaviconConfiguration implements ResourceLoaderAware {

			private final ResourceProperties resourceProperties;

			private ResourceLoader resourceLoader;

			public FaviconConfiguration(ResourceProperties resourceProperties) {
				this.resourceProperties = resourceProperties;
			}

			@Override
			public void setResourceLoader(ResourceLoader resourceLoader) {
				this.resourceLoader = resourceLoader;
			}

			@Bean
			public SimpleUrlHandlerMapping faviconHandlerMapping() {
				SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
				mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
				mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
				return mapping;
			}

			@Bean
			public ResourceHttpRequestHandler faviconRequestHandler() {
				ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
				requestHandler.setLocations(resolveFaviconLocations());
				return requestHandler;
			}

			private List<Resource> resolveFaviconLocations() {
				String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
				List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
				Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add);
				locations.add(new ClassPathResource("/"));
				return Collections.unmodifiableList(locations);
			}

		}

	}

这里通过了SimpleUrlHandlerMapping 进行了路径的映射

下一节

下一节:Spring boot 配置文件和ymal结构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值