我们正在使用速度来解析我们的模板。
Velocity 开发人员指南建议为每次解析创建一个新的 VelocityContext
但是VelocityEngine
和RuntimeInstances
呢?
我们可以重复使用它们还是每次调用都创建新实例更好?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();
}