首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

FreeMarker Configuration 核心配置詳解:共享變量、模板加載與緩存策略

     編輯:Java 相關知識

概述

freemarker.template.Configuration 是 FreeMarker 的核心配置對象,通常作為單例使用。它負責:

  • 應用級全局設置(編碼、區域、數字格式等)
  • 共享變量管理(所有模板可見)
  • 模板加載、解析、緩存

共享變量

通過 cfg.setSharedVariable(name, value) 註冊,所有關聯模板自動可用。內建共享變量包括:

名稱類
capture_outputfreemarker.template.utility.CaptureOutput
compressfreemarker.template.utility.StandardCompress
html_escapefreemarker.template.utility.HtmlEscape
normalize_newlinesfreemarker.template.utility.NormalizeNewlines
xml_escapefreemarker.template.utility.XmlEscape

警告: 多線程環境(如 Servlet)切勿使用非線程安全的 TemplateModel 實現作為共享變量。

配置參數層級覆蓋機制

FreeMarker 採用三層覆蓋模型:

  1. Configuration 層:默認值,如 cfg.setSetting("locale", "zh_CN")
  2. Template 層:單個模板實例調用 template.setLocale() 覆蓋
  3. Environment 層:模板執行時通過 <#setting locale="en_US"> 指令覆蓋

優先級:Environment > Template > Configuration。可查閱 Configurable.setSetting 獲取所有可配置參數。

模板加載器

三種內建方式:

// 1. 文件目錄
cfg.setDirectoryForTemplateLoading(new File("/path/to/templates"));

// 2. Classpath 資源(推薦生產環境,可打包進 JAR)
cfg.setClassForTemplateLoading(YourClass.class, "/templates");

// 3. Web 應用上下文
cfg.setServletContextForTemplateLoading(servletContext, "/WEB-INF/templates");

多源加載: 使用 MultiTemplateLoader 組合多個加載器,按順序查找:

TemplateLoader[] loaders = {
    new FileTemplateLoader(new File("/tmp/templates")),
    new FileTemplateLoader(new File("/usr/data/templates")),
    new ClassTemplateLoader(getClass(), "")
};
cfg.setTemplateLoader(new MultiTemplateLoader(loaders));

自定義加載器只需實現 freemarker.cache.TemplateLoader 接口。

模板緩存策略

FreeMarker 默認緩存模板對象,每 5 秒檢查一次文件更新(update_delay 參數)。高併發系統建議調整緩存存儲:

// 兩級 LRU 緩存:強引用區 20,軟引用區 250
cfg.setCacheStorage(new MruCacheStorage(20, 250));
// 或通過字符串設置
cfg.setSetting(Configuration.CACHE_STORAGE_KEY, "strong:20, soft:250");

手動清理緩存:cfg.clearTemplateCache()。

異常處理體系

階段異常類型說明
初始化IOException / ParseException配置文件讀取/解析錯誤
模板加載/解析IOException模板文件不存在、無權限
模板加載/解析ParseException模板語法錯誤
模板執行IOException輸出流寫入失敗
模板執行TemplateException運行時錯誤(如變量不存在)

最佳實踐建議

  • 應用啟動時構建單例 Configuration,設置 setDefaultEncoding("UTF-8")。
  • 生產環境使用 ClassTemplateLoader,配合 JAR 打包發布。
  • 高併發場景調大強引用緩存區(如 50-100),減少重複解析開銷。
  • 統一異常處理:捕獲 TemplateException 記錄日誌,返回友好錯誤頁。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved