Spring应用集成Freemarker加载spring.ftl时遇FileNotFoundException
问题解决:Spring集成Freemarker时FileTemplateLoader找不到模板目录
问题原因
你使用FileTemplateLoader加载模板,但spring.ftl位于库模块的src/main/resources/templates下,打包后该目录会被嵌入到jar包的classpath中,并非本地文件系统的物理目录。FileTemplateLoader仅能读取文件系统中的文件,因此会抛出FileNotFoundException。
解决方案
将FileTemplateLoader替换为ClassTemplateLoader,它支持从classpath中加载资源,适配jar包内的模板文件。
修改后的配置代码
private static Configuration getConfig() throws IOException, TemplateException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); cfg.setFallbackOnNullLoopVariable(false); // 替换为ClassTemplateLoader,从classpath加载templates目录 // 第一个参数传入当前类的Class对象,第二个参数为classpath下的模板根路径 cfg.setTemplateLoader(new ClassTemplateLoader(YourConfigClass.class, "/templates")); Properties settings = new Properties(); settings.setProperty("auto_import", "/spring.ftl as spring"); cfg.setSettings(settings); return cfg; }
关键说明
ClassTemplateLoader的第二个参数"/templates"对应库中src/main/resources/templates目录,打包后该目录会被放置到classpath根目录下。YourConfigClass需替换为当前getConfig方法所在的类,或任何能访问到该classpath资源的类。auto_import配置无需修改,/spring.ftl会被ClassTemplateLoader正确解析为classpath下templates/spring.ftl。
内容的提问来源于stack exchange,提问作者Ousmane MBINTE
相关产品推荐
相关产品推荐

