简体   繁体   中英

Spring Boot + FreeMarker + RestController loading templates

I'm using FreeMarker as a way to construct strings that are properties of a POJO I put on the wire as a response to a REST request. I've added Freemarker to the project's Maven pom and I can inject the configuration in to my services, though I have to do one peculiar thing in order to get the classloader to find my templates.

     private Template getTemplate() throws Exception {
        configuration.setClassForTemplateLoading(this.getClass(), "/template/");

        Template temp = configuration.getTemplate("test.ftl");

        return temp;
    }

Is there a cleaner way to configure where FreeMarker looks for templates? Using a @Bean to produce a FreeMarkerConfigurer isn't affecting the configuration at all.

http://freemarker.org/docs/pgui_config_templateloading.html

You can put ftl templates inside src/main/resources/templates folder and it will be automatically recognized for free marker version : 2.3.26-incubating in spring boot. Otherwise use the below code in application.properties file and autowire the object where used.

spring.freemarker.template-loader-path=relativefolder/

https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM