web-dev-qa-db-ja.com

src / main / resourcesフォルダーからFreemarkerテンプレートファイルを読み取る方法

私のコード(スプリングブートアプリケーション)からsrc/main/resourcesフォルダーに保存されているfreemarkerテンプレート(* .ftl)ファイルにアクセスする方法は?

私は次を試しました

freemarker.template.Configuration config = new Configuration();
configuration.setClassForTemplateLoading(this.getClass(), "/resources/templates/");

そして、次の例外を取得

freemarker.template.TemplateNotFoundException: Template not found for name "my-template.ftl".
27
yathirigan

クラスパスのルートはsrc/main/resources、パスを変更します

configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
47
Nathan Hughes

「freemarker.template.TemplateNotFoundException:名前のテンプレートが見つかりません...」問題に直面していました。コードは正しかったのですが、pom.xmlに/ templates /ディレクトリを含めるのを忘れていました。そこで、以下のコードで問題を修正しました。これがお役に立てば幸いです。

 AppConfig.Java :

    @Bean(name="freemarkerConfiguration")
    public freemarker.template.Configuration getFreeMarkerConfiguration() {
        freemarker.template.Configuration config = new freemarker.template.Configuration(freemarker.template.Configuration.getVersion());
        config.setClassForTemplateLoading(this.getClass(), "/templates/");
        return config;
    }

 EmailSenderServiceImpl.Java:

    @Service("emailService")
    public class EmailSenderServiceImpl implements EmailSenderService 
    {
        @Autowired
        private Configuration freemarkerConfiguration;

        public String geFreeMarkerTemplateContent(Map<String, Object> dataModel, String templateName)
        {
            StringBuffer content = new StringBuffer();
            try {
                content.append(FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(templateName), dataModel));
                return content.toString();
            }
            catch(Exception exception) {
                logger.error("Exception occured while processing freeMarker template: {} ", exception.getMessage(), exception);
            }
            return "";
        }
    }


 pom.xml :

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
                <includes>
                    <include>templates/*.ftl</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/</directory>
                <includes>
                    <include>templates/*.ftl</include>
                </includes>
            </resource>
        </resources>

    </build>


2
Ved Singh