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

yat*_*gan 27 spring freemarker maven spring-boot

如何从我的代码(Spring Boot应用程序)访问存储在src/main/resources文件夹中的freemarker模板(*.ftl)文件?

我尝试了以下内容

freemarker.template.Configuration config = new Configuration();
configuration.setClassForTemplateLoading(this.getClass(), "/resources/templates/");
Run Code Online (Sandbox Code Playgroud)

并获得以下异常

freemarker.template.TemplateNotFoundException: Template not found for name "my-template.ftl".
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 49

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

configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
Run Code Online (Sandbox Code Playgroud)

  • 这样就救了我脱掉头发!谢谢 (3认同)

Ved*_*ngh 6

我面临“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>


Run Code Online (Sandbox Code Playgroud)