创建配置实例

首先,您必须创建一个freemarker.template.Configuration实例并调整其设置。 Configuration实例是存储 FreeMarker 的应用程序级别设置的中心位置。此外,它还处理预解析模板(即Template对象)的创建和“缓存”。

通常,在应用程序(可能是 servlet)生命周期开始时,您只能一次

// Create your Configuration instance, and specify if up to what FreeMarker
// version (here 2.3.29) do you want to apply the fixes that are not 100%
// backward-compatible. See the Configuration JavaDoc for details.
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);

// Specify the source where the template files come from. Here I set a
// plain directory for it, but non-file-system sources are possible too:
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));

// From here we will set the settings recommended for new projects. These
// aren't the defaults for backward compatibilty.

// Set the preferred charset template files are stored in. UTF-8 is
// a good choice in most applications:
cfg.setDefaultEncoding("UTF-8");

// Sets how errors will appear.
// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

// Don't log exceptions inside FreeMarker that it will thrown at you anyway:
cfg.setLogTemplateExceptions(false);

// Wrap unchecked exceptions thrown during template processing into TemplateException-s:
cfg.setWrapUncheckedExceptions(true);

// Do not fall back to higher scopes when reading a null loop variable:
cfg.setFallbackOnNullLoopVariable(false);

从现在开始,您应该使用此单个配置实例(即,其单例)。但是请注意,如果系统有多个使用 FreeMarker 的独立组件,则它们当然将使用自己的私有Configuration实例。

Warning!

不要不必要地重新创建Configuration实例;这很昂贵,尤其是因为您丢失了模板缓存。 Configuration个实例意味着是应用程序级别的单例。

在此之后,在多线程应用程序(如网站)中,不得再修改Configuration实例中的设置。因此,它可以被视为“有效不变”的对象,因此您可以 continue 使用“安全发布”技术(请参阅 JSR 133 和相关文献)以使实例可用于其他线程。例如,通过最终文件或 volatile 文件或通过线程安全的 IoC 容器(如 Spring 提供的容器)发布实例。 Configuration不处理修改设置的方法是线程安全的。