SpringBoot la introducción Banner

A, Banner Introducción

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

Se muestra más arriba, es cada vez que comenzamos SpringBoot contenido cuando el proyecto estará en la salida del controlador, este es el Banner .

Modo de salida de 1.2 bandera

* LOG:将 banner 信息输出到日志文件。
* CONSOLE:将 banner 信息输出到控制台。
* OFF:禁用 banner 的信息输出。

En segundo lugar, Banner personalizado

2.1 bandera de texto

En resourcesel nuevo directorio banner.txtde archivos, de la siguiente manera:

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
*/

Iniciar el proyecto, ver la salida de la consola:

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
*/

Podemos ver la bandera estilo ha cambiado.

2.2 Estilos de imágenes Banner

La resourcescreación bajo el banner.jpgarchivo

Iniciar el proyecto, ver la salida de la consola:

          &&&&&&&&&&                                       &&                 
        &&&       :                                        &&                 
       &&*                                                 &&                 
      &&&                8888888*    :******     &&&&&&&&: &&   8888888       
      &&&      &&&&&&&& 88&    888  **     **:  &&     &&: &&  88:   .88      
       &&           && 888      88 ***      ** &&.     &&: && :8888888        
        &&&        &&&  88      88 ***     *** &&&     &&: &&  88.            
         8&&&&&&&&&&    .88888888   *********   &&&&&&&&&: &&   88888888      
             :&&.          .8&         .**         o&  &&*        .88         
                                               .&&    .&&                     
                                                 &&&&&&&             

En tercer lugar, modificar el nombre de archivo predeterminado

bandera es SpringBoot nombre por defecto, también podemos personalizar el nombre del archivo.

3.1 especificar el nombre de archivo del archivo de configuración

# 文本形式
spring.banner.location=icon.txt
# 图片形式
spring.banner.image.location=icon.jpg    

3.2 Especificar el nombre del archivo de formato de código

public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(SpringbootApplication.class);
    springApplication.setBanner(new ResourceBanner(new ClassPathResource("icon.txt")));
    springApplication.run();
}

En cuarto lugar, el modo de modificación

4.1 modo de modificación a través del archivo de configuración

spring.main.banner-mode=off

4.2 Modificación forma de código de modo

public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(SpringbootApplication.class);
    springApplication.setBannerMode(Banner.Mode.LOG);
    springApplication.run();
}

Cinco, la salida de los principios de la bandera

Introduzca runMétodos: encontrado un printBannermétodo:

public ConfigurableApplicationContext run(String... args) {
    ......
    try{
        ......
        Banner printedBanner = printBanner(environment);
        ......
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);    
        ......    
    }catch (Throwable ex) {
        ......
    }   
    
}    

Nos fijamos en su implementación:

private Banner printBanner(ConfigurableEnvironment environment) {
    // 判断 banner 模式
    if (this.bannerMode == Banner.Mode.OFF) {
        return null;
    }
    // 获取资源加载器
    ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
            : new DefaultResourceLoader(getClassLoader());
  
    SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
    // 判断将 banner 输出到日志还是控制台
    if (this.bannerMode == Mode.LOG) {
        return bannerPrinter.print(environment, this.mainApplicationClass, logger);
    }
    return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}

En el printmétodo:

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

En el getBannermétodo:

private Banner getBanner(Environment environment) {
    Banners banners = new Banners();
    // 获取图片 banner
    banners.addIfNotNull(getImageBanner(environment));
    // 获取文本 banner
    banners.addIfNotNull(getTextBanner(environment));
    // 判断是否存在一个 banner
    if (banners.hasAtLeastOneBanner()) {
        return banners;
    } 
    // 后备 banner
    if (this.fallbackBanner != null) {
        return this.fallbackBanner;
    }
    // 默认 banner
    return DEFAULT_BANNER;
}

Ver dos de adquisición de Bannemétodos

// 默认文件名
static final String BANNER_LOCATION_PROPERTY = "spring.banner.location";
// 默认图片名
static final String BANNER_IMAGE_LOCATION_PROPERTY = "spring.banner.image.location";

private Banner getImageBanner(Environment environment) {
    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;
    }
    for (String ext : IMAGE_EXTENSION) {
        Resource resource = this.resourceLoader.getResource("banner." + ext);
        if (resource.exists()) {
            return new ImageBanner(resource);
        }
    }
    return null;
}

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

Imprime clase de implementación ImageBanner :

@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
    String headless = System.getProperty("java.awt.headless");
    try {
        System.setProperty("java.awt.headless", "true");
        printBanner(environment, out);
    }
    catch (Throwable ex) {
        logger.warn(LogMessage.format("Image banner not printable: %s (%s: '%s')", this.image, ex.getClass(),
                ex.getMessage()));
        logger.debug("Image banner printing failure", ex);
    }
    finally {
        if (headless == null) {
            System.clearProperty("java.awt.headless");
        }
        else {
            System.setProperty("java.awt.headless", headless);
        }
    }
}

private void printBanner(Environment environment, PrintStream out) throws IOException {
    int width = getProperty(environment, "width", Integer.class, 76);
    int height = getProperty(environment, "height", Integer.class, 0);
    int margin = getProperty(environment, "margin", Integer.class, 2);
    boolean invert = getProperty(environment, "invert", Boolean.class, false);
    BitDepth bitDepth = getBitDepthProperty(environment);
    PixelMode pixelMode = getPixelModeProperty(environment);
    Frame[] frames = readFrames(width, height);
    for (int i = 0; i < frames.length; i++) {
        if (i > 0) {
            resetCursor(frames[i - 1].getImage(), out);
        }
        printBanner(frames[i].getImage(), margin, invert, bitDepth, pixelMode, out);
        sleep(frames[i].getDelayTime());
    }
}

Enfoque readFrames método:

private Frame[] readFrames(int width, int height) throws IOException {
    try (InputStream inputStream = this.image.getInputStream()) {
        try (ImageInputStream imageStream = ImageIO.createImageInputStream(inputStream)) {
            return readFrames(width, height, imageStream);
        }
    }
}
private Frame[] readFrames(int width, int height, ImageInputStream stream) throws IOException {
    Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
    Assert.state(readers.hasNext(), "Unable to read image banner source");
    ImageReader reader = readers.next();
    try {
        ImageReadParam readParam = reader.getDefaultReadParam();
        reader.setInput(stream);
        int frameCount = reader.getNumImages(true);
        Frame[] frames = new Frame[frameCount];
        for (int i = 0; i < frameCount; i++) {
            frames[i] = readFrame(width, height, reader, i, readParam);
        }
        return frames;
    }
    finally {
        reader.dispose();
    }
}   

En sexto lugar, el sello de producción de sitios recomendados en línea

portal

ventajas:

  • Al cambiar de fuentes y el texto de entrada, la palabra será la bandera de salida automáticamente.
  • En el cuadro de salida es editable, puede agregar un número de versión, información sobre el autor y por lo tanto sobre sí mismo.

desventajas:

  • No se puede descargar txt.
  • Resultados Sólo seleccionados copiar el contenido manualmente y pegarlo en el archivo banner.txt.

Supongo que te gusta

Origin www.cnblogs.com/markLogZhu/p/12508463.html
Recomendado
Clasificación