Spring boot中Freemarker依赖父级项目,寻找资源

问题

为了继承公共的父项目html静态资源,,我们希望在子项目相同路径下有文件时,覆盖父项目资源文件,没有的时候直接获取父项目。
但是freemark在寻找视图的时候,发现无法找到父类静态视图资源。

解决

在配置文件中增加以下配置

# Whether to prefer file system access for template loading. 
#File system access enables hot detection of template changes.
spring.freemarker.prefer-file-system-access=false

根据官方解释为:
是否优先从从文件系统中获取模板,以支持热加载,默认为true。

从官方文档描述中,得出以下结论:
1、如果设置true,会优先使用文件路径获取【咦,这不是废话吗?】。
2、如果设置为false,不支持热加载数据。
但是经过实践发现,以上结论都是错误的!!!

我们要继承父项目,读取父模板内容,需要设置prefer-file-system-access=false,否则会报404无法找到视图。
并且设置为false后,数据热加载测试依然可以正常运行。

那是什么原因导致api文档和实际操作过程中截然不同的答案呢?我们研究下源码

原因

从入口开始追踪

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
    public boolean isPreferFileSystemAccess() {
        return this.preferFileSystemAccess;
    }

    public void setPreferFileSystemAccess(boolean preferFileSystemAccess) {
        this.preferFileSystemAccess = preferFileSystemAccess;
    }
}

看下图,我们可以看到freferFileSystemAccess字段,只被方法isPreferFileSystemAccess调用。

preferFileSystemAccess调用链.png

跟踪方法到了核心判定方法:

public class FreeMarkerConfigurationFactory {
    protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) {
        if (isPreferFileSystemAccess()) {
            // Try to load via the file system, fall back to SpringTemplateLoader
            // (for hot detection of template changes, if possible).
            try {
                Resource path = getResourceLoader().getResource(templateLoaderPath);
                File file = path.getFile();  // will fail if not resolvable in the file system
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Template loader path [" + path + "] resolved to file path [" + file.getAbsolutePath() + "]");
                }
                return new FileTemplateLoader(file);
            }
            catch (Exception ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Cannot resolve template loader path [" + templateLoaderPath +
                            "] to [java.io.File]: using SpringTemplateLoader as fallback", ex);
                }
                return new SpringTemplateLoader(getResourceLoader(), templateLoaderPath);
            }
        }
        else {
            // Always load via SpringTemplateLoader (without hot detection of template changes).
            logger.debug("File system access not preferred: using SpringTemplateLoader");
            return new SpringTemplateLoader(getResourceLoader(), templateLoaderPath);
        }
    }
}

我们看到,这里进行逻辑区分,看起来true没问题。只能跟踪下代码
true:优先从资源文件中获取,如果异常,走fasle逻辑
false:new SpringTemplateLoader(getResourceLoader(), templateLoaderPath);

跟踪代码发现:
这个代码仅在初始化执行,判定文件目录是否存在,并非文件是否存在。
所以会导致后续使用时,直接使用FileTemplateLoader,导致无法正常加载。我们再来验证下:

/*---------FreeMarkerConfigurationFactory begin---------*/

List<TemplateLoader> templateLoaders = new ArrayList<>(this.templateLoaders);
if (this.templateLoaderPaths != null) {
            for (String path : this.templateLoaderPaths) {
                templateLoaders.add(getTemplateLoaderForPath(path));
            }
        }
...
//对象转数组,创建TemplateLoader 对象
TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
//config设置loader对象
config.setTemplateLoader(loader);
        
/*---------FreeMarkerConfigurationFactory end--------*/

讲loader放入对象

public class TemplateCache {
    private final TemplateLoader templateLoader;
    public TemplateCache(TemplateLoader templateLoader, ...) {
        this.templateLoader = templateLoader;
   }
}

我们可以看到templateLoader最终使用场景

templateloader调用链.png

太多了,不过没关系,研究过freemarker渲染逻辑知道。获取视图核心源码:

 final MaybeMissingTemplate maybeTemp = cache.getTemplate(name, locale, customLookupCondition, encoding, parseAsFTL);
//继续跟进
 Template template = getTemplateInternal(name, locale, customLookupCondition, encoding, parseAsFTL);

可以看到我们440行,既是读取loader。

    lastModified = lastModified == Long.MIN_VALUE ? templateLoader.getLastModified(source) : lastModified;            
            Template template = loadTemplate(
                    templateLoader, source,
                    name, newLookupResult.getTemplateSourceName(), locale, customLookupCondition,
                    encoding, parseAsFTL);
            cachedTemplate.templateOrException = template;
            cachedTemplate.lastModified = lastModified;
            storeCached(tk, cachedTemplate);

但是,通过断点返现,没有运行到440行,被前面420行代码截胡了

                newLookupResult = lookupTemplate(name, locale, customLookupCondition);
                
                if (!newLookupResult.isPositive()) {
                    storeNegativeLookup(tk, cachedTemplate, null);
                    return null;
                }

最终结果策略模式一阵绕,到了代码代码791即,上面以后一行

       //策略模式?
       @Override
        public TemplateLookupResult lookup(TemplateLookupContext ctx) throws IOException {
            return ctx.lookupWithLocalizedThenAcquisitionStrategy(ctx.getTemplateName(), ctx.getTemplateLocale());
        }

    private Object findTemplateSource(String path) throws IOException {
        final Object result = templateLoader.findTemplateSource(path);
        if (LOG.isDebugEnabled()) {
            LOG.debug("TemplateLoader.findTemplateSource(" +  StringUtil.jQuote(path) + "): "
                    + (result == null ? "Not found" : "Found"));
        }
        return modifyForConfIcI(result);
    }

ok,至此,我们可以确认,最后的加载策略,就是通过初始化的loader进行加载的.
我们来看下,两种classLoader最后的区别:

spring.freemarker.prefer-file-system-access=true
spring.freemarker.prefer-file-system-access=false

可以看到,如果设置为false,我们使用的是SpringTemplateLoader.
SpringTemplateLoader如何实现读取父目录的代码的呢?

2个问题

为什么要用策略模式
中间420都截胡了,后面440代码还有什么用呢。

继续未完的游戏

templateLoader.findTemplateSource(path);
如何可以实现,有文件的时候优先读取文件,没有文件的时候读取父项目中的内容。

        for (TemplateLoader templateLoader : templateLoaders) {
            if (lastTemplateLoader != templateLoader) {
                Object source = templateLoader.findTemplateSource(name);
                if (source != null) {
                    if (sticky) {
                        lastTemplateLoaderForName.put(name, templateLoader);
                    }
                    return new MultiSource(source, templateLoader);
                }
            }
        }

拥有两个对象,file对象在上面,classLoader在下面,故会优先读取file中的内容。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容