创建一个使用速度的可重用解析方法

Create a reusable parse method which uses velocity

我们正在使用 velocity 来解析我们的模板。

Velocity developer guide 建议为每次解析创建一个新的 VelocityContext

但是 VelocityEngineRuntimeInstances 呢?

我们可以重用它们还是每次调用都创建新实例更好? VelocityEngine 的新实例会导致内存泄漏吗?

  public String parse(String templateStr, Map<String, String> params) {
        StringWriter writer = new StringWriter();
        try {
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init();
            RuntimeServices rs = RuntimeSingleton.getRuntimeServices();
            StringReader sr = new StringReader(templateStr);
            SimpleNode sn = rs.parse(sr, "template");

            Template t = new Template();
            t.setRuntimeServices(rs);
            t.setData(sn);
            t.initDocument();

            VelocityContext context = new VelocityContext();

            if (params != null && !params.isEmpty()) {
                for (Entry<String, String> entry : params.entrySet()) {
                    context.put(entry.getKey(), entry.getValue());
                }
            }
            t.merge(context, writer);
        } catch (Exception e) {
            LOGGER.error("Exception in velocity parsing", e);

        }
        return writer.toString();

    }

Velocity 允许您使用 Singleton model

Velocity.setProperty(Velocity.RUNTIME_LOG_NAME, "mylog");
Velocity.init();
Template t = Velocity.getTemplate("foo.vm");

Developers have two options for using the Velocity engine, the singleton model and the separate instance model. The same core Velocity code is used for both approaches, which are provided to make Velocity easier to integrate into your Java application.

基本上,您可以使用 Velocity class:

而不是 VelocityEngine

This class provides a separate new-able instance of the Velocity template engine. The alternative model for use is using the Velocity class which employs the singleton model.

RuntimeInstance 是内部 class 你不必处理。

VelocityEngine,以及单例 class Velocity(依赖于 VelocityEngine),是可重入的(以及它们相关的模板资源加载器).这意味着它们可以安全地用于多线程环境。