Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法
有时候我们需要封装一些自己的类库,使其能够应用到各个项目中,对于Freemarker类库的封装,官方有介绍,并且Freemarker支持Loading templates from multiple locations,使得封装起来更简单。对于基于Spring Boot构建的项目,对Freemarker类库的封装也有简单的方法。
Spring Boot默认从classpath:/templates/
下加载模板文件,那么我们用Maven构建模块的时候,在通用模块下,/resources
下建相同的目录结构,是不是就能实现简单的封装呢?答案是肯定的,见下图:

Paste_Image.png
speedy-ext
是整个项目中的通用模块,可以在其他项目中复用,由于shiro官方并没有对Freemarker支持的类库,所以在这里我封装了一个Shiro的Freemarker类库,放到通用模块中。
speedy-sample
是web模块,也就是整个业务所在,依赖 speedy-ext
。

Paste_Image.png
我需要在index.ftl
中引入shiro.ftl

Paste_Image.png
但是当我们访问/index
时,却报错了:

Paste_Image.png
我们还需要将spring.freemarker.prefer-file-system-access
设置为false
才行!

Paste_Image.png
大功告成!
总结
其实就一句话,将自定义的类库放到同样的模板目录下classpath:/templates
,然后将Application.properties
中的spring.freemarker.prefer-file-system-access
设置为false
就可以了。