如何从src / main / resources文件夹中读取Freemarker模板文件?

时间:2015-06-29 13:33:47

标签: spring maven spring-boot freemarker

如何从我的代码(Spring Boot应用程序)访问存储在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".

2 个答案:

答案 0 :(得分:41)

类路径的根目录是src/main/resources,将路径更改为

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

答案 1 :(得分:2)

我遇到了“ 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>