Apache Velocity 禁用模板和资源缓存



我有一个弹簧启动应用程序,该应用程序揭示了呈现相对简单的速度模板的API。该模板使用#parse包括其他几个模板,否则将写出一些从Java层传递给它的基本变量。这些模板在JAR文件中,因此它们是从类路径加载的。我使用以下速度引擎设置,该设置是在正式中创建的:

    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.setProperty("classpath.resource.loader.cache", "false");
    ve.setProperty("velocity.engine.resource.manager.cache.enabled", "false");
    ve.setProperty("resource.manager.cache.enabled", "false");
    ve.init();

模板的多个部分旨在是唯一的每次要求(资源用作对简单的弹簧MVC控制器的响应),因此我需要禁用模板资源的缓存。我尝试了上述配置,并在src/main/resources中的velocity.properties文件中定义它,但是在我重新启动应用程序之前更改模板或文件不会"生效"。

做本文档页面所说的事情似乎无济于事(实际上您可以看到它在上面做什么)。

上面的引擎代码位于Spring Component类中,即使将VelocityEngine的东西移至静态最终字段,并且每次都没有帮助。

如何迫使弹簧/速度加载模板&每次都包括资源?

您只需要classpath.resource.loader.cache配置密钥。而且由于所有速度默认值的缓存都符合false,您甚至不需要它。

另外,无需按每个请求重新定位VelocityEngine。

我使用以下小测试程序进行了检查,该程序在修改时正确重新加载的资源:

import java.io.PrintWriter;
import java.io.Writer;
import java.util.Scanner;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;    
public class Test
{
    public static void main(String args[])
    {
        try
        {
            VelocityEngine ve = new VelocityEngine();
            ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
            ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
            // next line not needed since 'false' is the default
            // ve.setProperty("classpath.resource.loader.cache", "false");
            ve.init();
            VelocityContext context = new VelocityContext();
            Writer writer = new PrintWriter(System.out);
            Scanner scan = new Scanner(System.in);
            while (true)
            {
                System.out.print("> ");
                String str = scan.next();
                context.put("foo", str);
                ve.mergeTemplate("test.vm", "UTF-8", context, writer);
                writer.flush();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

如果在您的情况下不起作用,尤其是如果您在每个请求下重新启动速度,那么它肯定是Spring本身中的classLoader缓存问题。

因此,您应该检查春季热交换指南,以查看如何禁用缓存。我想一个对春天有更好了解的人可以为您提供有关在这种特殊情况下如何进行的暗示。

令人尴尬的是,这是因为我需要一旦更改模板或资源来编译Intellij,例如使用CTRL F9。感谢@claude Brisson的帮助。

最新更新