spring打包jar后,freemarker报错:cannot be resolved to absolute file path because it does not reside in the

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring打包jar后,freemarker报错:cannot be resolved to absolute file path because it does not reside in the相关的知识,希望对你有一定的参考价值。

spring打包jar后,freemarker报错:cannot be resolved to absolute file path because it does not reside in the file system:

java.io.FileNotFoundException: class path resource [mytemp/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/我的jar包所在位置!/BOOT-INF/classes!/mytemp/

现象:用idea做了一个简单的spring web工程,用freemarker作为模板框架,事先将一个模板文件:demo_temp.yaml放到工程的resources/mytemp目录下面,mytemp是我自己新建的目录,最终,模板文件在项目中的路径是resources/mytemp/demo_temp.yaml。按照freemarker的例子,在代码中:

...

freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_29);

Resource resource = new ClassPathResource("mytemp/");
cfg.setDirectoryForTemplateLoading(resource.getFile());

...

以上代码在本地跑没有问题,可以正常从resources/mytemp/temp_demo.yaml文件加载出来并正确赋值生成,但是把项目打包成一个jar文件,通过命令

java -jar xxx.jar

运行后,freemarker报错,错误代码在:cfg.setDirectoryForTemplateLoading(resource.getFile());

原因是当没有打包,在本地时候,Java系统可以通过文件系统方式访问到demo_temp.yaml,但是打包成jar文件后,就没有普通本地上那种文件路径,导致找不到demo_yaml文件。

解决方案,换掉原先的以文件路径方式(setDirectoryForTemplateLoading)的模板加载方式,改用类路径访问:

freemarker.template.Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_29);
        configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(),"/mytemp/");

特别注意打头的  / ,mytemp前面的  / 需要加。如果没有 / , 系统将会只在当前类的包下寻找mytemp/demo_temp.yaml,如果是 /mytemp/  系统将会在整个工程代码的根目录出发寻找。

这里freemarker官方文档对setClassForTemplateLoading给出的解释:

  • void setClassForTemplateLoading(Class cl, String basePackagePath) and void setClassLoaderForTemplateLoading(ClassLoader classLoader, String basePackagePath): These are for when you want to load templates via the same mechanism with which Java loads classes (from the class-path, as they used to say vaguely). This is very likely be the preferred means of loading templates for production code, as it allows you to keep everything inside the deployment jar files. The first parameter decides which Java ClassLoader will be used. The second parameter specifies the package that contains the templates, in /-separated format. Note that if you don't start it with /, it will be interpreted relatively to the package of the Class parameter.

出处链接:

Template loading - Apache FreeMarker Manualhttps://freemarker.apache.org/docs/pgui_config_templateloading.html

以上是关于spring打包jar后,freemarker报错:cannot be resolved to absolute file path because it does not reside in the的主要内容,如果未能解决你的问题,请参考以下文章

Spring boot: 运行maven打包的jar包报错-jar中没有主清单属性

spring cloudIDEAMavenspring cloud多模块打包,打包的jar包只有几k,jar包无法运行,运行报错:no main manifest attribute, i

spring maven项目打包为可执行jar包

Spring---springboot修改打包后的项目(jar war)名称

Maven打包后运行报错

Maven打包后运行报错