美文网首页
Spring boot中Freemarker依赖父级项目,寻找资

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

作者: 北海北_6dc3 | 来源:发表于2019-03-06 18:28 被阅读0次

    问题

    为了继承公共的父项目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中的内容。

    相关文章

      网友评论

          本文标题:Spring boot中Freemarker依赖父级项目,寻找资

          本文链接:https://www.haomeiwen.com/subject/wchxpqtx.html