java - Apache Velocity 2.0 如何编写自定义资源加载器?
问题描述
API文档中有一个ResourceLoader
类:
我想实现自己的加载器,因为我需要从数据库加载模板,但是以上下文敏感的方式(换句话说:DataSourceResourceLoader 不能使用,我需要编写自定义代码以从数据库)。
似乎ResourceLoader
有一些抽象方法,而且我似乎也可以通过实现这些抽象方法来编写自定义加载器。但是我看不到任何方法可以向引擎添加新的加载程序。没有“addResourceLoader”方法。该文档仅显示了如何配置 Velocity 内置的加载器:
https://velocity.apache.org/engine/2.0/developer-guide.html#resource-loaders
主要问题:如何将自定义资源加载器添加到 VelocityEngine(或 VelocityContext?)
另一个问题:我想关闭所有内置加载程序。特别WebappResourceLoader
是默认情况下处于活动状态,并且在我的特定应用程序中代表安全风险。怎么做?
解决方案
我无法回答如何实现自己的资源加载器,但第二部分非常简单:
创建 VelocityEngine 时,可以传递定义资源加载器的“类路径”的属性
不同的类加载器由属性键的前缀标识。所以像:
Properties props = new Properties();
// Add a default class path resource loader - just an example
props.setProperty("cp.resource.loader.class", ClasspathResourceLoader.class.getName());
props.setProperty("cp.resource.loader.cache", "true);
// Add your own resource loader
props.setProperty("db.resource.loader.class", MyDBResourceLoader.class.getName());
props.setProperty("db.resource.loader.cache", "false");
// Define the "class path" for the loaders
// in this case first the "db" loader is asked for resources, if nothing is found the "cp" loader
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "db,cp");
// Now create the engine
VelocityEngine engine = new VelocityEngine(props);
上面只为该引擎定义了两个资源加载器,该引擎实例不会使用其他加载器。
推荐阅读
- node.js - 使用 n 切换节点版本
- casting - 在 Ada 中将地址拆分并转换为不同的整数
- python - ModuleNotFoundError:没有名为“sklearn.linear_model.base”的模块
- reactjs - 反应原生 AWS 放大背景图像
- python - 神经网络为数据集中的每个示例预测相同的答案序列
- postgresql - 在 postgresql 中,如何在 char 中保留空格
- python - FCM 推送通知在使用 Python 的 AWS Lambda 中不起作用
- variadic-functions - 帕斯卡可变数量的函数参数
- html - CSS图像网格,每个图像都有悬停效果
- salesforce - Salesforce:如何让用户选择多个产品并将其分配给单个机会?