freemarker.template.Configuration 是 FreeMarker 的核心配置對象,通常作為單例使用。它負責:
通過 cfg.setSharedVariable(name, value) 註冊,所有關聯模板自動可用。內建共享變量包括:
| 名稱 | 類 |
|---|---|
| capture_output | freemarker.template.utility.CaptureOutput |
| compress | freemarker.template.utility.StandardCompress |
| html_escape | freemarker.template.utility.HtmlEscape |
| normalize_newlines | freemarker.template.utility.NormalizeNewlines |
| xml_escape | freemarker.template.utility.XmlEscape |
警告: 多線程環境(如 Servlet)切勿使用非線程安全的 TemplateModel 實現作為共享變量。
FreeMarker 採用三層覆蓋模型:
cfg.setSetting("locale", "zh_CN")template.setLocale() 覆蓋<#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 打包發布。TemplateException 記錄日誌,返回友好錯誤頁。