Java Velocity 引擎初始化问题

标签 java initialization velocity

我编写了一个包含邮件构建部分的库。这个邮件构建部分使用了 Velocity。 mailbuilder类如下--

public class mailBuilder {
 public void initialize() throws Exception
    {
            Properties props = new Properties();

            log.info("About to set the ClassPath for Velocity specific tasks");
            props.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            props.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName());

            try
            {
                log.info("Just before");
                Velocity.init(props);
                log.info("Just after");
            }
            catch ( Exception e )
            {
                log.error( "Caught Execption on velocityEngine init", e );
                throw new Exception( "Caught Execption on velocityEngine init", e );
            }
            log.info("Completed initializing Velocity Engine");

    }

public String returnMailstring() throws Exception {
initialize();
....
....
}

}

现在,当我像从 eclipse 一样运行和测试这个库时,结果符合预期,一切似乎都很好。 我有一个 Web 应用程序,它从 UI 接收请求,并使用 ExecutorService (newSingleThreadExecutor) 在后台静默地为这些用户请求一个一个地服务。

我注意到我对上述库的调用在邮件构建部分挂起,特别是在 Velocity.init(props) 没有抛出异常,但线程似乎在 VelocityEngine 初始化时挂起. 我在网上查了一下,但对问题所在一无所知。 关于这个问题的任何帮助都是巨大的。

谢谢 p1ng

最佳答案

速度使用有两种模型:

  1. 单例模型,即 Velocity.init(..),在这里您的应用程序中只有一个速度配置。在这种情况下,您应该在应用程序启动时通过监听器或任何类型的初始化 bean 仅调用一次 init。
  2. 多模型从 1.2 版开始,您可以使用多个配置使用多个速度引擎,模型是这样使用的:
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;

...


//  create a new instance of the engine
 VelocityEngine ve = new VelocityEngine();


//  configure the engine.  In this case, we are using
//  ourselves as a logger (see logging examples..)


ve.setProperty(
    VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);

//  initialize the engine
ve.init();

...

Template t = ve.getTemplate("foo.vm");

因此,只需选择您希望使用的模型并遵循它即可。但是以线程方式调用 Velocity.init() 肯定会有不良行为。

关于Java Velocity 引擎初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8668839/

相关文章:

java - 在 Java 中初始化泛型

java - 导出项目到jar时出现"java.lang.IllegalStateException: Toolkit not initialized"

java - Camel + 速度 : how to put things in Velocity context

apache - 如何在速度模板中进行重定向?

velocity - Velocity 中的条件运算符

java - @Autowired 不在构造函数中创建成员

java - 使用简单 XML 进行特殊解析 XML

java - 重新部署后无效的 Jboss 数据源

java - 一般而言,哪种 Java ORM 被认为是性能最高的?

javascript - 为什么它已经是一个窗口属性?