This is the first day of my participation in Gwen Challenge

This article is participating in “Java Theme Month – Java Development in Action”, see the activity link for details

I am Chen PI, an ITer of Internet Coding. I search “Chen PI’s JavaLib” on wechat and read the latest articles as soon as possible, reply to [information], and then I can get the technical materials, electronic books, interview materials of first-line big factories and excellent resume templates carefully arranged by me.

preface

When we start the Spring Boot project, we print the Spring logo and version information on the console by default, as follows:

This is the Banner printing function of Spring Boot. In fact, we can customize the printed Banner, also can disable and enable the Banner printing function. In real projects, we usually don’t customize the banner pattern, it’s just a print pattern or text at the start of the project, it doesn’t make any sense. It is recommended that you play with this egg in your personal project and have a brief understanding of its internal implementation.

For example, after customizing a banner, the project launch console prints something like this:

Realize the principle of

Spring the Boot has an interface org. Springframework. Boot. Banner specifically implement this operation. To customize a printBanner, simply define a class that implements the interface and override the printBanner method to print. When the Springboot project starts, our implementation class object is created and its printBanner method is called.

package org.springframework.boot;

import java.io.PrintStream;

import org.springframework.core.env.Environment;

/** * Interface class for writing a banner programmatically@since1.2.0 * /
@FunctionalInterface
public interface Banner {

	/** * Print the banner to the specified stream. *@param environment the spring environment
	 * @param sourceClass the source class for the application
	 * @param out the output print stream
	 */
	void printBanner(Environment environment, Class
        sourceClass, PrintStream out);

	// Enumeration value used to configure the Banner
	enum Mode {
		// Turn off banner printing
		OFF,
        // Prints banners to the console
		CONSOLE,
		// Prints banners to log files
		LOG
	}
}
Copy the code

The default Banner implementation class

Springboot has several built-in Banner implementation classes. When Springboot is started, different Banner implementation classes are selected to print Banner information. Mainly ImageBanner, ResourceBanner, SpringBootBanner these three implementation classes.

  1. When the project is started, it will determine whether certain conditions are true (whether the banner file exists in the project), and then it will be createdImageBannerResourceBannerClass and use them to print the banner.
  2. If not, check whether there is our custom Banner implementation classfallbackBanner, if present, use it to print the banner pattern.
  3. Otherwise, the default is usedSpringBootBannerImplement the class to print the banner, which we often seeSpringPattern.
// Get the available Banner implementation class
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;
	}
	// SpringBootBanner implementation class
	return DEFAULT_BANNER;
}
Copy the code

ImageBanner

Org. Springframework. Boot. ImageBanner class is specially loading pictures and print the banner. It checks the application configuration file. If there is a configuration of spring proeprties. Banner. Image. The value of the variable location, this value to specify to load images are available, and if there is the build ImageBanner object. If there is no configuration variable, the Classpath is also checked for image files that start with banner and end with.gif,.jpg,.png, and if so, the ImageBanner object is constructed.

class SpringApplicationBannerPrinter {

	static final String BANNER_IMAGE_LOCATION_PROPERTY = "spring.banner.image.location";

	static final String[] IMAGE_EXTENSION = { "gif"."jpg"."png" };

	// Get the ImageBanner object
	private Banner getImageBanner(Environment environment) {
	    / / load spring. Banner. Image. The location specified file, file exists, build ImageBanner object
		String location = environment.getProperty(BANNER_IMAGE_LOCATION_PROPERTY);
		if (StringUtils.hasLength(location)) {
			Resource resource = this.resourceLoader.getResource(location);
			return resource.exists() ? new ImageBanner(resource) : null;
		}
		// find the banner.gif, banner.jpg, banner.png files
		for (String ext : IMAGE_EXTENSION) {
			Resource resource = this.resourceLoader.getResource("banner." + ext);
			if (resource.exists()) {
				return newImageBanner(resource); }}return null; }}Copy the code

ResourceBanner

Org. Springframework. Boot. ResourceBanner class is specially loading and banner printed character. It checks if the configuration file application.proeprties has the configured value of the spring.banner. Location variable, which can be used to specify the file to load, and builds the ResourceBanner object if it does. If no variable is configured, the resource path is also checked to see if the banner.txt file exists, and if so, a ResourceBanner object is constructed.

class SpringApplicationBannerPrinter {

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

	static final String DEFAULT_BANNER_LOCATION = "banner.txt";

	// Get the ResourceBanner object
	private Banner getTextBanner(Environment environment) {
		String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
		Resource resource = this.resourceLoader.getResource(location);
		if (resource.exists()) {
			return new ResourceBanner(resource);
		}
		return null; }}Copy the code

To customize our banner, we create a banner. TXT file in the resources directory of our project and fill it with the text we want to print. For example, I fill the banner. TXT file with the Chen Pi content and then start the project.

SpringBootBanner

If the project does not set the above two custom banners (ImageBanner and ResourceBanner), then by default, the SpringBootBanner implementation class prints the banner. This is the printing Spring pattern we see on the console when we start the Springboot project. The source code is as follows:

package org.springframework.boot;

import java.io.PrintStream;

import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment;

/** * Default Banner implementation which writes the 'Spring' banner. */
class SpringBootBanner implements Banner {
	// This is the pattern we see on the console when we start the Springboot project
	private static final String[] BANNER = { "".____ ____ _"."/\\\\ / ___'_ ___ _(_)_ __ ___ \\\\ \\\\".\ \ "(() ___ | '_ |' _ | | '_ \ \ / _ ` | \ \ \ \ \ \ \ \"."\ \ \ \ / ___) | | _) | | | | | | | (_ | |))))".There comes "| |. __ _ - | | | _ _ - | | | _ \ \ __, | / / / /"."= = = = = = = = = | _ | = = = = = = = = = = = = = = | ___ / = / _ / _ / _ /" };

	private static final String SPRING_BOOT = " :: Spring Boot :: ";

	private static final int STRAP_LINE_SIZE = 42;

	@Override
	public void printBanner(Environment environment, Class
        sourceClass, PrintStream printStream) {
		for(String line : BANNER) { printStream.println(line); } String version = SpringBootVersion.getVersion(); version = (version ! =null)?" (v" + version + ")" : "";
		StringBuilder padding = new StringBuilder();
		while (padding.length() < STRAP_LINE_SIZE - (version.length() + SPRING_BOOT.length())) {
			padding.append(""); } printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, AnsiColor.DEFAULT, padding.toString(), AnsiStyle.FAINT, version)); printStream.println(); }}Copy the code

Realize the Banner class

Previously said we can implement the Banner class, rewrite the printing method, to achieve a custom Banner printing function.

package com.chenpi;

import java.io.PrintStream;
import org.springframework.boot.Banner;
import org.springframework.core.env.Environment;

/ * * *@DescriptionCustom Banner implementation class *@Author Mr.nobody
 * @Date 2021/6/4
 * @Version1.0 * /
public class MyBanner implements Banner {

    @Override
    public void printBanner(Environment environment, Class
        sourceClass, PrintStream out) {

      String banner = " .__ .__ \n"
          + " ____ | |__ ____ ____ ______ |__|\n"
          + "_/ ___\\| | \\_/ __ \\ / \\ \\____ \\| |\n"
          + "\\ \\___| Y \\ ___/| | \\ | |_> > |\n"
          + " \\___ >___| /\\___ >___| / | __/|__|\n"
          + "\ \ / \ \ / \ \ / \ \ | __ |"; out.println(banner); }}Copy the code

Create a custom Banner implementation object and set it to the Banner property of the SpringApplication class object. Ultimately the value of this attribute will be assigned to the SpringApplicationBannerPrinter fallbackBanner attributes of objects, interested can start the debug tracking.

package com.chenpi;

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

@SpringBootApplication
public class SpringBootBannerApplication {
	public static void main(String[] args) {
		SpringApplication springApplication = new SpringApplication(SpringBootBannerApplication.class);
		// Set a custom Banner
		springApplication.setBanner(new MyBanner());
		/ / start SpringBootspringApplication.run(args); }}Copy the code

Banner style control

The Buddha figure at the beginning of the article, you will notice, is emerald green. In fact, Springboot allows us to change the color of our banner, font italic, bold and so on. SpringBoot provides us with three enumerated classes to set these styles.

  1. AnsiColor: Sets the foreground of the character; referenceorg.springframework.boot.ansi.AnsiColorEnumeration type.
  2. AnsiBackground: Sets the background color of the character. referenceorg.springframework.boot.ansi.AnsiBackgroundEnumeration type.
  3. AnsiStyle: Set the character bold, italic, underline, etc. referenceorg.springframework.boot.ansi.AnsiStyleEnumeration type.

Also, you can reference some global variables in the banner.txt file, such as:

  1. ${spring-boot.version} : spring boot version number;
  2. ${spring-boot.formatted-version} : Displays the formatted Spring Boot version number.
  3. ${application.version} : the version number in the manifest.mf file;
  4. ${application. Formatted formatted version} : Displays the version number in the manifest.mf file.

Not only that, but we can also refer to the variables we defined in the configuration file application.properties. For example, the following variables are defined in the configuration file:

application.auth=chenpi
Copy the code

The contents of the banner. TXT file are as follows:

${AnsiColor.BRIGHT_GREEN}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// ". "88 //
/ / / / (| ^_^ |)
// O\ = /O //
/ / consists of / ` - '\ ____ / /
/ /. '\ \ | | / / `. / /
: / / / \ \ | | | | | | / / / / /
/ / / _ | | | | | - : - | | | | | - / / /
/ / | | \ \ \ / / / | | / /
/ / | \ _ | '\ - /' | | / /
// \.-\__ '-' ___/-. //
// ___ '... '/--... --...... //
. / /. "" '< ` ___ \ _ < | > _ / ___." "' > '. / /
/ / | | : ` - \ `; ` \ _ / `; . ` / - ` : | | / /
// \ \ '-.\ _ __\ /__ _/.-' // //
/ / = = = = = = = = ` - ____ ` - ___ \ _____ / ___ - ` _____. - '= = = = = = = = / /
/ / ` = - = '/ /
/ / ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ / /
// Buddha bless never crash and never BUG //
////////////////////////////////////////////////////////////////////
${AnsiColor.BRIGHT_CYAN}
Application Version: ${application.version}${application.formatted-version}
Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}

By -- ${application.auth}
Copy the code

Start the project and print the following banner on the console:

Banner pattern

In the Banner interface there is an enumeration class defined that defines the possible enumeration values for configuring the Banner, as follows:

@FunctionalInterface
public interface Banner {

	// Enumeration value used to configure the Banner
	enum Mode {
		// Turn off banner printing
		OFF,
        // Prints banners to the console
		CONSOLE,
		// Prints banners to log files
		LOG
	}
}
Copy the code

So we can choose to turn off the banner, print the banner to the console or log file, as follows:

package com.chenpi;

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

@SpringBootApplication
public class SpringBootBannerApplication {
    public static void main(String[] args) {
         SpringApplication springApplication = new SpringApplication(SpringBootBannerApplication.class);
         / / close the banner
         springApplication.setBannerMode(Mode.OFF);
         / / start SpringBootspringApplication.run(args); }}Copy the code

You can also set this value in the configuration file as follows

spring.main.banner-mode=off
Copy the code

If the startup class and configuration file are configured with the banner switch, the banner switch set in the configuration file takes precedence over the banner switch set in the startup class.

Banner generating tool

Some people may ask how to edit the Buddha’s patterns. In fact, there are many online tools that can make ASCII characters and patterns according to our input content or pictures.

  • Customize ASCII characters: network-science.de/ ASCII /
  • Customized ASCII picture: www.degraeve.com/img2txt.php