user2759013
user2759013

Reputation: 501

Spring FreeMarkerConfiguration Template Loader Path overwritten by Configuration

I have a Java based web app running with Spring 4. I'm using FreeMarker for my web templates. My WebConfig class uses a FreeMarkerConfigurer object to set up my template loader path and some other settings as so:

@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException {
    FreeMarkerConfigurer fmc = new FreeMarkerConfigurer();
    fmc.setTemplateLoaderPath("/WEB-INF/templates");
    fmc.setDefaultEncoding("UTF-8");
    Properties settings = new Properties();
    settings.setProperty("date_format", "dd MMM yyyy");
    fmc.setFreemarkerSettings(settings);
    return fmc;
}

This works fine: views resolve correctly, including any <#import 'spring.ftl' as spring> directives which can be loaded from the jar.

Now I want to customise my application more, for example setting a custom template exception handler. I've created a FreeMarker Configuration object and added this to the FreeMarkerConfigurer:

Configuration cfg = new Configuration();
cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());
fmc.setConfiguration(cfg);

But this stops my views resolving - it seems to overwrite the TemplateLoaderPath from the FreeMarkerConfigurer object and I have to explicitly set the path in the Configuration instance instead for my templates to be located by the project:

cfg.setDirectoryForTemplateLoading(new File("C:/myProject/WEB-INF/templates"));

Additionally, spring.ftl is no longer loaded from the jar and I have to put a copy in my template directory for it to be loaded.

Why does adding a Configuration to a FreeMarkerConfigurer overwrite my template loader path? Is my setup incorrect or does a Configuration have greater priority?

Upvotes: 1

Views: 3449

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

FreeMarkerConfigurer is just a factory that helps to build a freemarker.template.Configuration and exposes it with its method getConfiguration().

If you want to further configurate the configuration, extract it first from your configurer, because there will be only one Configuration used by FreeMarker.

Upvotes: 2

Related Questions