Skip to content

Allow customization of the banner printer used by SpringBootApplication #42284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.core.env.Environment;

/**
* Class used by {@link SpringApplication} to print the application banner.
*
* @author Phillip Webb
* @author Junhyung Park
*/
class DefaultSpringApplicationBannerPrinter implements SpringApplicationBannerPrinter {

private static final Log logger = LogFactory.getLog(DefaultSpringApplicationBannerPrinter.class);

@Override
public Banner print(Environment environment, Class<?> sourceClass, Banner.Mode bannerMode, Banner banner) {
banner.printBanner(environment, sourceClass, System.out);
switch (bannerMode) {
case OFF:
case LOG:
try {
logger.info(createStringFromBanner(banner, environment, sourceClass));
}
catch (UnsupportedEncodingException ex) {
logger.warn("Failed to create String for banner", ex);
}
case CONSOLE:
banner.printBanner(environment, sourceClass, System.out);
}
return new PrintedBanner(banner, sourceClass);
}

private String createStringFromBanner(Banner banner, Environment environment, Class<?> mainApplicationClass)
throws UnsupportedEncodingException {
String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) {
banner.printBanner(environment, mainApplicationClass, out);
}
return byteArrayOutputStream.toString(charset);
}

/**
* Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {

private final Banner banner;

private final Class<?> sourceClass;

PrintedBanner(Banner banner, Class<?> sourceClass) {
this.banner = banner;
this.sourceClass = sourceClass;
}

@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass;
this.banner.printBanner(environment, sourceClass, out);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package org.springframework.boot;

import java.io.IOException;
import java.lang.StackWalker.StackFrame;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
Expand Down Expand Up @@ -56,7 +57,6 @@
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
Expand Down Expand Up @@ -93,6 +93,7 @@
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.io.support.SpringFactoriesLoader.ArgumentResolver;
Expand Down Expand Up @@ -180,6 +181,7 @@
* @author Tadaya Tsuyukubo
* @author Lasse Wulff
* @author Yanming Zhou
* @author Junhyung Park
* @since 1.0.0
* @see #run(Class, String[])
* @see #run(Class[], String[])
Expand Down Expand Up @@ -215,6 +217,8 @@ public class SpringApplication {

private Banner banner;

private SpringApplicationBannerPrinter bannerPrinter;

private ResourceLoader resourceLoader;

private BeanNameGenerator beanNameGenerator;
Expand Down Expand Up @@ -557,13 +561,39 @@ private Banner printBanner(ConfigurableEnvironment environment) {
if (this.properties.getBannerMode(environment) == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
: new DefaultResourceLoader(null);
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
if (this.properties.getBannerMode(environment) == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
SpringApplicationBannerPrinter bannerPrinter = Objects.requireNonNullElseGet(this.bannerPrinter,
DefaultSpringApplicationBannerPrinter::new);
Banner banner = this.banner;
if (banner == null) {
banner = getFallbackBanner(environment);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
return bannerPrinter.print(environment, this.mainApplicationClass, this.properties.getBannerMode(environment),
banner);
}

private Banner getFallbackBanner(Environment environment) {
Banner textBanner = getTextBanner(environment);
if (textBanner != null) {
return textBanner;
}
return new SpringBootBanner();
}

private Banner getTextBanner(Environment environment) {
if (this.resourceLoader == null) {
return null;
}
String location = environment.getProperty(BANNER_LOCATION_PROPERTY, BANNER_LOCATION_PROPERTY_VALUE);
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
return new ResourceBanner(resource);
}
}
catch (IOException ex) {
// Ignore
}
return null;
}

/**
Expand Down Expand Up @@ -1036,6 +1066,15 @@ public void setBannerMode(Banner.Mode bannerMode) {
this.properties.setBannerMode(bannerMode);
}

/**
* Sets the {@link SpringApplicationBannerPrinter} used to print the banner. Defaults
* to {@link SpringApplicationBannerPrinter}.
* @param bannerPrinter the printer used to print the banner
*/
public void setBannerPrinter(SpringApplicationBannerPrinter bannerPrinter) {
this.bannerPrinter = bannerPrinter;
}

/**
* Sets if the application information should be logged when the application starts.
* Defaults to {@code true}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,118 +16,26 @@

package org.springframework.boot;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.logging.Log;

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
* Class used by {@link SpringApplication} to print the application banner.
* Interface class used to print the application banner.
*
* @author Phillip Webb
* @author Junhyung Park
* @since 3.4.0
*/
class SpringApplicationBannerPrinter {

static final String BANNER_LOCATION_PROPERTY = "spring.banner.location";

static final String DEFAULT_BANNER_LOCATION = "banner.txt";

private static final Banner DEFAULT_BANNER = new SpringBootBanner();
public interface SpringApplicationBannerPrinter {

private final ResourceLoader resourceLoader;
String BANNER_LOCATION_PROPERTY = "spring.banner.location";

private final Banner fallbackBanner;

SpringApplicationBannerPrinter(ResourceLoader resourceLoader, Banner fallbackBanner) {
this.resourceLoader = resourceLoader;
this.fallbackBanner = fallbackBanner;
}

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);
}

Banner print(Environment environment, Class<?> sourceClass, PrintStream out) {
Banner banner = getBanner(environment);
banner.printBanner(environment, sourceClass, out);
return new PrintedBanner(banner, sourceClass);
}

private Banner getBanner(Environment environment) {
Banner textBanner = getTextBanner(environment);
if (textBanner != null) {
return textBanner;
}
if (this.fallbackBanner != null) {
return this.fallbackBanner;
}
return DEFAULT_BANNER;
}
String DEFAULT_BANNER_LOCATION = "banner.txt";

private Banner getTextBanner(Environment environment) {
String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
return new ResourceBanner(resource);
}
}
catch (IOException ex) {
// Ignore
}
return null;
}

private String createStringFromBanner(Banner banner, Environment environment, Class<?> mainApplicationClass)
throws UnsupportedEncodingException {
String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) {
banner.printBanner(environment, mainApplicationClass, out);
}
return byteArrayOutputStream.toString(charset);
}

/**
* Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {

private final Banner banner;

private final Class<?> sourceClass;

PrintedBanner(Banner banner, Class<?> sourceClass) {
this.banner = banner;
this.sourceClass = sourceClass;
}

@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass;
this.banner.printBanner(environment, sourceClass, out);
}

}
Banner print(Environment environment, Class<?> sourceClass, Banner.Mode mode, Banner banner);

static class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar {
class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar {

@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.BootstrapRegistryInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationBannerPrinter;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.ApplicationContext;
Expand Down Expand Up @@ -337,6 +338,11 @@ public SpringApplicationBuilder bannerMode(Banner.Mode bannerMode) {
return this;
}

public SpringApplicationBuilder bannerPrinter(SpringApplicationBannerPrinter bannerPrinter) {
this.application.setBannerPrinter(bannerPrinter);
return this;
}

/**
* Sets if the application is headless and should not instantiate AWT. Defaults to
* {@code true} to prevent java icons appearing.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.boot.Banner.Mode;
import org.springframework.boot.testsupport.system.CapturedOutput;
import org.springframework.boot.testsupport.system.OutputCaptureExtension;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mock.env.MockEnvironment;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for {@link DefaultSpringApplicationBannerPrinter}.
*
* @author Moritz Halbritter
* @author Junhyung Park
*/
@ExtendWith(OutputCaptureExtension.class)
class DefaultSpringApplicationBannerPrinterTests {

@Test
void shouldUseUtf8(CapturedOutput capturedOutput) {
ResourceLoader resourceLoader = new GenericApplicationContext();
Resource resource = resourceLoader.getResource("classpath:/banner-utf8.txt");
SpringApplicationBannerPrinter printer = new DefaultSpringApplicationBannerPrinter();
printer.print(new MockEnvironment(), DefaultSpringApplicationBannerPrinterTests.class, Mode.LOG,
new ResourceBanner(resource));
assertThat(capturedOutput).containsIgnoringNewLines("\uD83D\uDE0D Spring Boot! \uD83D\uDE0D");
}

}
Loading
Loading