栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot 工程读取 resources 目录下的 freemarker 模板

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot 工程读取 resources 目录下的 freemarker 模板

一开始使用的是 FileTemplateLoader ,本地 IDE 中运行没有问题,但是打包成 jar 包运行就报错了,因为模板文件在 jar 包中。下面是报错内容:

java.io.FileNotFoundException: class path resource [templates] cannot be resolved to absolute file path because it does not reside in the file system

之后看了 TemplateLoader 的所有实现,发现了 SpringTemplateLoader,这是 Spring 提供的实现,使用它就没问题了。下面是代码示例:

@Autowired
private ResourceLoader resourceLoader;

...

// 模板存放在 resources 下的 templates 目录下
SpringTemplateLoader templateLoader = new SpringTemplateLoader(resourceLoader, "classpath:templates");
Configuration configuration = new Configuration(new Version("2.3.31"));
configuration.setTemplateLoader(templateLoader);
Template template = configuration.getTemplate("model.ftl");

还有一点需要注意,传入 Template 的 Map 不能使用 name 为 id 的 key,在模板内读取 id 的值时读到的是和包名类似的值,而不是传入的值。用其它比如:id_ 等替代即可。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926603.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号