Search code examples
javaspring-bootfreemarker

How to resolve error: freemarker.template.TemplateNotFoundException and specify custom path for load template file in FreeMarker with Spring Boot


Resolve error:

freemarker.template.TemplateNotFoundException: Template not found for name . The name was interpreted by this TemplateLoader: LegacyDefaultFileTemplateLoader(baseDir="", canonicalBasePath="" Warning: The "template_loader" FreeMarker setting wasn't set (Configuration.setTemplateLoader), and using the default value is most certainly not intended and dangerous, and can be the cause of this error.


Solution

  • To specify a custom path from which to read the template file in Java Spring Boot just create a method like this that creates a custom FileTemplateLoader:

    public freemarker.template.Configuration getConfiguration() throws IOException {
        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(templateBasePath));
        freemarker.template.Configuration config = new freemarker.template.Configuration();
        config.setTemplateLoader(fileTemplateLoader);
        return config;
    }
    

    rather than:

    @Bean
    public FreeMarkerConfigurationFactoryBean freemarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        bean.setTemplateLoaderPath("classpath:/templates/");
        return bean;
    }