spring boot 整合Freemarker

添加依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-freemarkerartifactId>
dependency>

配置属性文件


spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/

注册Bean


@org.springframework.context.annotation.Configuration
public class FreeMarkerConfig {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Bean
    public Configuration getFreeMarkerConfiguration(){
        return freeMarkerConfigurer.getConfiguration();
    }

    public void resolveMap(Map model, String templateName){
        try {
            Template template = this.getFreeMarkerConfiguration().getTemplate(templateName);
            template.process(model, new OutputStreamWriter(System.out));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}

编写ftl文件


hello world
${name}
${age}
this is test

测试


@Autowired
FreeMarkerConfig fc;
@Test
public void FreeMarkerConfigTest(){
    Map result = new HashMap<>();
    result.put("name","test");
    result.put("age","20");
    fc.resolveMap(result,"index.ftl");
}

附言


这个只是将模板引擎加载进来,将渲染后的结果输出到控制台,也可以采用别的办法输出到文件或者返回一个string。本人刚开始学spring,哪里有错误的地方,欢迎指正交流。

你可能感兴趣的:(spring)