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

标签 java velocity spark-framework

我正在 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

最佳答案

试试这个:

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

     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
    
  3. x.int();

这里重要的一点是您不会在每次请求时都再次初始化速度引擎。在创建速度引擎对象时做这样的事情:

  VelocityEngine x;   // instance variable

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

关于java - 如何在不重新加载服务器的情况下重新加载模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35612330/

相关文章:

java - 有没有办法在 Android 上对 java 进程的部分进行沙箱处理?

java - Android 应用程序无法运行、崩溃

java - 速度动态属性访问

Apache Velocity foreach 循环#continue

java - Spark框架: Listen for server stop

java - Jsoup 在没有类或标签的情况下获取不同标签之间的特定数据

java - m2e可以安装外部jar文件吗?还是需要安装maven命令行工具?

intellij-idea - 在 Velocity 或 IntelliJ 文件模板中将驼峰字符串转换为蛇形大小写或破折号大小写

java - 如何使用spark框架正确闪烁消息