Create a configuration instance

First you have to create a freemarker.template.Configuration instance and adjust its settings. A Configuration instance is a 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.22) 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_22);

// 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:
cfg.setDefaultEncoding("UTF-8");

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

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.

Warning!

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

When using in multi-threaded applications (like for Web sites), the settings in the Configuration instance must not be modified anymore after this point. Then 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 the other threads. Like, publish the instance through a final or volatile filed, or through a thread-safe IoC container, but not through a plain field. (Configuration methods that don't deal with modifying settings are thread-safe.)

FreeMarker Manual -- For FreeMarker 2.3.22
HTML generated: 2015-02-28 21:34:03 GMT
Edited with XMLMind XML Editor
Here!