引言

Velocity是一款非常高效的基于Java语言的模板引擎,应用十分广泛,尤其是应用在各类代码生成场景如现在非常流行的mybatis-plus-generator的默认模板引擎采用的就是Velocity。

目前,互联网上有很多关于Velocity教程的技术博客,然而多数文章的代码逻辑十分混乱,层次不清,多数仅仅只是实现了基本功能而已。为此,本系列博客将只介绍必要的、最少的代码,同时非常注重代码的逻辑,力求为大家提供最简明、最清晰的教程。

目标

  • 快速掌握Velocity的基本用法;

方法

  • 实例化VelocityEngine对象实例;
  • 准备context数据;
  • 准备writer对象;
  • 获得template对象并调用merge()方法;
  • 测试模板生成结果。

代码

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import java.io.*;
import java.util.Properties;

public class Client {
public static void main(String[] args) throws IOException {

// (1) 获得engine实例对象;
Properties p = new Properties();
p.setProperty("file.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

VelocityEngine velocityEngine = new VelocityEngine(p);
velocityEngine.init();

// (2.1) 准备context;
Context context = new VelocityContext();
context.put("name", "bob");

// (2.2) 准备writer;
Writer writer = new StringWriter();

// (2.3) 开始合并生成;
// Template template = new Template(); // !!!易出错点
Template template = velocityEngine.getTemplate("demo.vm"); //
template.merge(context, writer);

// (3) 测试合并结果
System.out.println(writer.toString());
}
}

resources/demo.vm文件

hello, ${name}.