gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:29:49 25 4
gpt4 key购买 nike

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

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.

基本上,而不是 VelocityEngine ,您可以使用 Velocity 类:

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.

关于java - 创建一个使用速度的可重用解析方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com