如何将 spring.freemarker.template-loader-path 指向依赖项 jar 中的模板?

How do I point spring.freemarker.template-loader-path to the templates within a dependency jar?

我有 2 个项目。一个项目 (A) 包含我所有的核心功能,例如我的 entities/services/daos 等。它还包含许多我希望在我的另一个项目 (B) 中利用和重用的 .ftl 模板。我已经成功地 (B) 使用了 (A) 中的 类,但是我没有运气重用 freemarker 模板。

项目 (B) 是一个 Spring 引导应用程序 (v2.1.3),所以我认为我使用 application.property: spring.freemarker.template-loader-path 与定义新 @Bean.

由于是 spring-boot 应用程序,默认情况下,如果没有这个 属性,项目将在项目自己的 src/main/resources/templates 位置查找,但我的目标是项目(A ) 拥有 none 自己的模板,并让我的控制器 return 在项目 (B) 中找到的模板。

在我的 Maven 依赖项中,层次结构如下:

projectA-0.0.1.jar
    templates
        folder1
            exampleA.ftl
        folder2
            exampleB.ftl

目前我的控制器设置为 return 类似 return new ModelAndView("folder1/exampleA") 的内容,其中上下文前缀为 src/main/resources/templates/

有谁知道我需要给 spring.freemarker.template-loader-path 属性 的值的正确格式,以便指向我的依赖 jar 中的模板而不是本地 src/main/resources/templates ?

所以 spring.freemarker.template-loader-path=classpath:/templates/ 是我最初问题的答案,但是它没有解决我的问题。

将以下 @Bean 添加到我的配置 class 中,归功于@ddekany

@Bean public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() { FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean(); bean.setTemplateLoaderPath("classpath:/templates/"); return bean; }

虽然我可以使用属性,但由于其他因素,在我的场景中需要@Bean

它对我不起作用。 但这种方法确实有效:

    @Bean
    @Primary
    public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() throws IOException {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/templates");
        bean.setPostTemplateLoaders(ctl);
        return bean;
    }

我最终得到了以下 bean。如果您没有使用 spring-freemarker-starter maven 依赖项。我使用的是 simpleJavamail,所以不需要所有依赖项。

@Bean("freeMarkerConfiguration")
public freemarker.template.Configuration freeMarkerConfigurationFactoryBean() throws IOException {
    freemarker.template.Configuration freeMarkerConfiguration =
            new freemarker.template.Configuration(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    freeMarkerConfiguration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/templates"));
    return freeMarkerConfiguration;
}

设置为属性:

spring.freemarker.cache=false
spring.freemarker.template-loader-path=file:src/main/resources/templates/

对我有用。