Detailed Explanation of Custom Banner of SpringBoot
- 2021-11-13 01:41:03
- OfStack
1. Generate banner website online
https://www.bootschool.net/ascii
http://www.network-science.de/ascii/
http://patorjk.com/software/taag/
http://www.degraeve.com/img2txt.php
2. Two ways to customize Banner
Before customizing Banner, analyze the source code first, and the source code tracking analysis is as follows:
main method started by SpringBoot
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
// Open Banner Printing mode (OFF : Close, CONSOLE Console output, LOG : Log output )
springApplication.setBannerMode(Mode.LOG);
springApplication.run(args);
}
SpringApplication. printBanner ():
private Banner printBanner(ConfigurableEnvironment environment) {
// Whether to turn it on Banner Mode
if (this.bannerMode == Mode.OFF) {
return null;
} else {
ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader((ClassLoader)null);
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter((ResourceLoader)resourceLoader, this.banner);
return this.bannerMode == Mode.LOG ? bannerPrinter.print(environment, this.mainApplicationClass, logger) : bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
}
SpringApplicationBannerPrinter.print()
Banner print(Environment environment, Class<?> sourceClass, Log logger) {
// Call getBanner() Method
Banner banner = this.getBanner(environment);
try {
logger.info(this.createStringFromBanner(banner, environment, sourceClass));
} catch (UnsupportedEncodingException var6) {
logger.warn("Failed to create String for banner", var6);
}
return new SpringApplicationBannerPrinter.PrintedBanner(banner, sourceClass);
}
SpringApplicationBannerPrinter.getBanner()
private Banner getBanner(Environment environment) {
SpringApplicationBannerPrinter.Banners banners = new SpringApplicationBannerPrinter.Banners();
// Get first image Type of banner
banners.addIfNotNull(this.getImageBanner(environment));
// After getting text Type of banner
banners.addIfNotNull(this.getTextBanner(environment));
if (banners.hasAtLeastOneBanner()) {
// If at least there is 1 Is returned
// Banners It has also been realized Banner Interface, using combination mode, can actually print pictures and text at the same time banner .
return banners;
} else {
// Returns a custom banner(this.fallbackBanner) Or springboot Default banner(DEFAULT_BANNER)
// Default banner Class: SpringBootBanner .
// Custom banner : We need to imitate it SpringBootBanner To customize 1 Category
//this.fallbackBanner: Represents a custom banner This parameter can be used in the springboot Object of the startup class main Setting in the method , Introduction to the follow-up meeting
// public static void main(String[] args) {
// SpringApplication springApplication = new SpringApplication(Application.class);
// springApplication.setBanner(new MyBanner());// Custom banner
// springApplication.run(args);
// }
return this.fallbackBanner != null ? this.fallbackBanner : DEFAULT_BANNER;
}
}
Explanation: There are two ways to get banner. First, get banner of image type, then get banner of text type. If there is at least one banner, if not, return custom banner. If there is no custom banner, return default
So how to get banner of image type and Text type in the above source code?
SpringApplicationBannerPrinter.getImageBanner()
SpringApplicationBannerPrinter.getTextBanner()
// Get Text Type of banner
private Banner getTextBanner(Environment environment) {
// Start first spring.banner.location Path, if not, the default banner.txt
String location = environment.getProperty("spring.banner.location", "banner.txt");
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
return new ResourceBanner(resource);
}
} catch (IOException var5) {}
return null;
}
// Get image Type of banner
private Banner getImageBanner(Environment environment) {
String location = environment.getProperty("spring.banner.image.location");
if (StringUtils.hasLength(location)) {
Resource resource = this.resourceLoader.getResource(location);
return resource.exists() ? new ImageBanner(resource) : null;
} else {
String[] var3 = IMAGE_EXTENSION;
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
String ext = var3[var5];
Resource resource = this.resourceLoader.getResource("banner." + ext);
if (resource.exists()) {
return new ImageBanner(resource);
}
}
return null;
}
}
Image-based banner
Can be specified by configuring parameters spring. banner. image. location You can place a file named "banner. jpg" (which types depend on the definition of the ext constant) in the classpath directory (src/main/resources)File-based banner
Can be specified by the configuration parameter spring. banner. location You can place a file named "banner. txt" in the classpath directory (src/main/resources)After the source code analysis, how to customize it?
Type 1: Configuration mode (configure directly in properties or yml file)
That is, configure the spring. banner. image. location and spring. banner. location paths
Or
Put "Picture" and "banner. txt" in the classpath directory
spring.banner.location=classpath:banner1.png
spring.banner.image.margin=2
spring.banner.image.height=76
spring.banner.charset=UTF-8
spring.banner.image.invert=false
spring.banner.image.location=banner1.png
spring.main.banner-mode=console
spring.main.show-banner=true
Type 2: Custom banner
import org.springframework.boot.Banner;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment;
import java.io.PrintStream;
/** Customize banner Class
* @author hb
* @date 2021-09-09 10:39
*/
public class MyBanner implements Banner {
private static final String[] BANNER = new String[]{"", " . ____ _ __ _ _", " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", " ' |____| .__|_| |_|_| |_\\__, | / / / /", " =========|_|==============|___/=/_/_/_/"};
public MyBanner() {
}
@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
String[] bannerArray = BANNER;
int bannerLength = bannerArray.length;
for(int i = 0; i < bannerLength; ++i) {
String line = bannerArray[i];
out.println(line);
}
out.println(AnsiOutput.toString(new Object[]{AnsiColor.GREEN, " :: Spring Boot :: ", AnsiColor.DEFAULT, AnsiStyle.FAINT}));
out.println();
}
}
How do I use custom Banner?
Add a custom banner to the springboot startup class
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
// Add Custom banner
springApplication.setBanner(new MyBanner());
springApplication.run(args);
}
}
If you do not want to print banner, you can set springApplication. setBannerMode (Banner. Mode. OFF) in main of the startup class;
Or
Turn off printing of banner by parameter configuration spring. main. banner-mode=off
3. Control the banner style
Spring provides three enumeration classes to set the color of characters, namely:
AnsiColor : Used to set the foreground color of characters
AnsiBackground : Used to set the background color of characters
AnsiStyle : Used to control bold, italic, underline and so on.
4. Display application information
In addition to the styles specified above, you can also display 1 version information related to the application:
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
// Open Banner Printing mode (OFF : Close, CONSOLE Console output, LOG : Log output )
springApplication.setBannerMode(Mode.LOG);
springApplication.run(args);
}
0