spring boot源码学习 SpringApplication(二)-Banner

先说一下 banner相关的配置属性

#spring.main.bannerMode=off # 关闭banner打印
#banner.location=coffee.banne # 设置banner文本文件的位置 、相对于src/main/resources
#banner.image.location=11111.jpg #设置图片、打印的时候会乱码

代码中的用法

核心类 org.springframework.bootSpringApplicationBannerPrinter
核心代码
Banner printedBanner = printBanner(environment);
//如果没定义banner.location 会
private static final Banner DEFAULT_BANNER = new SpringBootBanner();

/** * 有时候可能会返回多个banner,如果按照我的想法 我可能会返回一个list * 但是 人家缺返回了一个banners噢 **/
private Banner getBanner(Environment environment, Banner definedBanner) {
        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;
    }

    private Banner getTextBanner(Environment environment) {
    //默认加载 banner.txt文件,可以在resources文件夹下新建一个 banner.txt
        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;
    }

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

看一下banners的实现,真的很巧妙

    private static class Banners implements Banner {

        private final List<Banner> banners = new ArrayList<Banner>();

        public void addIfNotNull(Banner banner) {
            if (banner != null) {
                this.banners.add(banner);
            }
        }

        public boolean hasAtLeastOneBanner() {
            return !this.banners.isEmpty();
        }

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

    }
    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/ID19870510/article/details/79187748
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞