Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法  作者 Devid 关注

2016.01.06 10:31 字数 341 阅读 2048评论 7喜欢 3

有时候我们需要封装一些自己的类库,使其能够应用到各个项目中,对于Freemarker类库的封装,官方有介绍,并且Freemarker支持Loading templates from multiple locations,使得封装起来更简单。对于基于Spring Boot构建的项目,对Freemarker类库的封装也有简单的方法。

Spring Boot默认从classpath:/templates/下加载模板文件,那么我们用Maven构建模块的时候,在通用模块下,/resources下建相同的目录结构,是不是就能实现简单的封装呢?答案是肯定的,见下图:

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Paste_Image.png

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

speedy-sample是web模块,也就是整个业务所在,依赖 speedy-ext

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Paste_Image.png

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

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Paste_Image.png

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

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Paste_Image.png

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

Spring Boot 将Freemarker打包到其他jar并在项目中引用的简单方法

Paste_Image.png

大功告成!

总结

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