Spring Boot应用中使用Freemarker模板发送邮件遇TemplateNotFoundException问题求助
问题排查与解决方法
嘿,这是个典型的Freemarker配置小坑,我帮你梳理清楚:
核心问题所在
你的FreeMarkerConfigurationFactoryBean配置写错了!setTemplateLoaderPath()这个方法是用来指定模板文件所在的根目录,而不是单个模板文件的路径。
你现在设置的是"classpath:templates/email-template.ftlh",这会让Freemarker误以为模板的根目录是classpath:templates/email-template.ftlh/,然后你调用getTemplate("email-template.ftlh")时,它就会去寻找classpath:templates/email-template.ftlh/email-template.ftlh——这显然不存在,所以才抛出TemplateNotFoundException。
修正后的配置代码
把模板加载路径改成模板所在的目录就行,也就是classpath:templates/:
@Bean public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() { FreeMarkerConfigurationFactoryBean fmConfigFactoryBean = new FreeMarkerConfigurationFactoryBean(); // 只指定模板目录,不是具体文件 fmConfigFactoryBean.setTemplateLoaderPath("classpath:templates/"); return fmConfigFactoryBean; }
额外的检查要点
- 确认模板文件名
email-template.ftlh拼写完全正确,尤其是大小写(Linux/macOS环境下文件名是区分大小写的) - 检查打包后的项目,确保
resources/templates目录和模板文件被正确复制到了classpath里(可以看target/classes/templates目录下有没有你的ftlh文件) - 如果你用的是Spring Boot 2.x及以上版本,其实可以不用手动配置这个Bean!Spring Boot默认会自动扫描
classpath:/templates/下的Freemarker模板,你可以尝试删掉这个自定义Bean,直接用自动配置,反而更不容易出错。
内容的提问来源于stack exchange,提问作者andrew17
相关产品推荐
相关产品推荐

