Create a configuration instance

First you have to create a freemarker.template.Configuration instance and adjust its settings. A Configuration instance is the central place to store the application level settings of FreeMarker. Also, it deals with the creation and caching of pre-parsed templates (i.e., Template objects).

Normally you will do this only once at the beginning of the application (possibly servlet) life-cycle:

// Create your Configuration instance, and specify if up to what FreeMarker
// version (here 2.3.25) 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_25);

// 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"));

// Set the preferred charset template files are stored in. UTF-8 is
// a good choice in most applications:

// Sets how errors will appear.
// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.

// Don't log exceptions inside FreeMarker that it will thrown at you anyway:

From now you should use this single configuration instance (i.e., its a singleton). Note however that if a system has multiple independent components that use FreeMarker, then of course they will use their own private Configuration instances.


Do not needlessly re-create Configuration instances; it's expensive, among others because you lose the template cache. Configuration instances meant to be application-level singletons.

In multi-threaded applications (like Web sites) the settings in the Configuration instance must not be modified anymore after this point. Thus it can be treated as "effectively immutable" object, so you can continue with safe publishing techniques (see JSR 133 and related literature) to make the instance available for other threads. Like, publish the instance through a final or volatile filed, or through a thread-safe IoC container (like the one provided by Spring). Configuration methods that don't deal with modifying settings are thread-safe.