java – 如何在不重新加载服务器的情况下重新加载模板?

我正在使用
Java / Spark框架中的应用程序,我正在使用Apache Velocity模板引擎.我的问题是,每次我更改模板中的任何内容时,我都必须重新加载整个服务器.有没有办法让某种热交换能够在不重新加载整个服务器的情况下处理模板?

private final VelocityEngine velocityEngine;

public VelocityTemplateEngine() {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "class");
    properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    properties.setProperty("class.resource.loader.cache", "true");
    properties.setProperty("class.resource.loader.modificationCheckInterval", "2");
    properties.setProperty("velocimacro.library.autoreload", "true");
    properties.setProperty("velocimacro.permissions.allow.inline.to.replace.global", "true");
    velocityEngine = new org.apache.velocity.app.VelocityEngine(properties);
    //velocityEngine.init(); <-- This bit of code does not change anything when uncommented...
}

解:
通过将resource.loader更改为file和class.resource.loader.class到org.apache.velocity.runtime.resource.loader.FileResourceLoader来解决此问题

properties.setProperty("resource.loader", "file");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

properties.setProperty("file.resource.loader.path", root + "/src/main/resources/"); // "root" points to the app folder

properties.setProperty("class.resource.loader.cache", "true"); // Enable cache
properties.setProperty("class.resource.loader.modificationCheckInterval", "2"); // Check for new files every 2 seconds

最佳答案 试试这个 :

>初始化速度引擎实例. VelocityEngine x = new VelocityEngine();
>设置属性:

 file.resource.loader.class= FileResourceLoader classname
 file.resource.loader.path=  template location
 file.resource.loader.cache= true
 file.resource.loader.modificationCheckInterval= duration in which you want to reload the templates

> x.int();

这里重要的一点是,您不会在每次请求时再次初始化速度引擎.在创建速度引擎对象时执行类似的操作:

  VelocityEngine x;   // instance variable

  if(x==null)
  {
   x = new VelocityEngine();
   x.init();
   }
  else
  {
   x;
   }
点赞