@SpringBootTest
public class FreemakerTest {
@Autowired
FreemarkerComponent freemarkerComponent;
@Test
public void freemakerTest() throws Exception {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Mike","123","女"));
studentList.add(new Student("Bill","456","男"));
String content = freemarkerComponent.getContent("hello", studentList);
System.out.println(content);
}
}
2.模板配置组件
@Component
@Slf4j
public class FreemarkerComponent {
@Value("${spring.freemarker.suffix}")
private String suffix;
@Autowired
private Configuration configuration;
/**
* <p>
* 拼接模板内容
* </p>
* @param temlateName 模板名称
* @param dataModel 数据模型
*/
public String getContent(String temlateName, Object dataModel) {
try {
temlateName += suffix;
Template template = configuration.getTemplate(temlateName);
StringWriter writer = new StringWriter();
Map<String, Object> map = new HashMap();
map.put("data", dataModel);
template.process(map, writer);
return writer.toString();
} catch (Exception e) {
log.error("根据模板[" + temlateName + "]得到结果时异常", e);
throw BizException.create(ResultCodeEnum.TEMPLATE_ERROR);
}
}
}
3.模板文件
[
<#list data as item>
{
"userName":"${item.username}",
"passWord":"${item.password}"
}
<#if item_has_next>
,
</#if>
</#list>
]
4.application.yml 中的freemaker配置
spring:
# 模板配置
freemarker:
charset: UTF-8
settings:
# 设置为兼容模式。当变量为null或者变量不存在时都不会抛出异常。
classic_compatible: true
# 数字格式化,格式化为6位小数
number_format: 0.######
# 模板存放地址,即/resources 后面的地址
template-loader-path: classpath:/ftl/
# 指定Freemarker模板文件的后缀名
suffix: .ftl
# 关闭模板缓存,方便测试
cache: false