spring boot配置freemarker--autoIncludes

来源:互联网 发布:南安普顿的人工智能 编辑:程序博客网 时间:2024/06/05 01:18

最近公司新开了个项目用了freemarker,在用宏的时候想在所有的模版都自动注入所以的宏模版。去看了spring boot的自动化配置的源码。感觉spring boot的配置好的spring boot不用变,想在spring boot的congiguration上改。

  1. 先注入spring boot的freemarkerProperties
    /**     * 拿到spring boot中的fm自动化配置     */    @Autowired    private FreeMarkerProperties properties;
  1. 覆盖FreeMarkerConfigurer
    /**     * 覆盖spring boot中的freemarker配置     *     * @return     */    @Bean    public FreeMarkerConfigurer freeMarkerConfigurer() {        //写入配置        FreeMarkerConfigurer factory = new FreeMarkerConfigurer();        writerProperties(factory);        //创建fm的配置,并且将factory中的信息写入到configuration中        Configuration configuration = null;        try {            configuration = factory.createConfiguration();            //和spring boot不同的部分,这部分是用来写入我们需要的freemarker configuration            List<String> autoIncludes = Lists.newArrayListWithCapacity(1);            //注意macro\macro.ftl这个路径是和在spring.freemarker.template-loader-path下            autoIncludes.add("macro\\macro.ftl");            configuration.setAutoIncludes(autoIncludes);        } catch (IOException e) {            e.printStackTrace();        } catch (TemplateException e) {            e.printStackTrace();        }        factory.setConfiguration(configuration);        return factory;    }    private void writerProperties(FreeMarkerConfigurer factory){        factory.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());        factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());        factory.setDefaultEncoding(this.properties.getCharsetName());        Properties settings = new Properties();        settings.putAll(this.properties.getSettings());        factory.setFreemarkerSettings(settings);    }
  1. marco.ftl包含所有的marco

注意这里的include路径也是在spring.freemarker.template-loader-path下的

<#include "macro/commonSelect.ftl"/><#include "macro/renderValue.ftl"/><#include "macro/bootSelect.ftl"/><#include "macro/dictToJson.ftl"/>

同理autoImport也可以通过同样的方式写入

0 0