简单几步,在spring boot中使用velocity模板生成文本:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>
2、resources中创建templates目录
3、创建.vm模板文件welcome.vm:
<html>
<body>
亲爱的${toUserName},你好!
${message}
祝:开心!
${fromUserName}
${time}
</body>
</html>
4、使用模板,测试用例:
@Autowired
VelocityEngine velocityEngine;
@Test
public void velocityTest(){
Map<String, Object> model = new HashMap<String, Object>();
model.put("time", XDateUtils.nowToString());
model.put("message", "这是测试的内容。。。");
model.put("toUserName", "张三");
model.put("fromUserName", "老许");
System.out.println(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "welcome.vm", "UTF-8", model));
}
5、测试结果:
附:
velocity语法参考:http://velocity.apache.org/engine/devel/vtl-reference.html
源代码参考:https://github.com/xujijun/my-spring-boot