[英]Loading Velocity Templates from nested JARs
我有一个打包在onejar中的应用程序,该应用程序使用Velocity进行模板化。
在我的Maven项目设置中,我在$base/src/main/resources/template.html
有一个文件。 当应用程序打包为onejar时,生成的onejar在其内部包含一个嵌套jar(在main / my-jar.jar下)。 反过来,该jar会将打包的template.html
文件打包在其根目录下。 (显然,maven将其从src / main / resources复制到了软件包的根目录中)
我想将该模板作为Velocity中的资源加载。 我已经读过我需要使用ClassPathResourceLoader来做到这一点,所以我有如下代码:
VelocityEngine ve = new VelocityEngine();
ve.setApplicationAttribute("resource.loader", "class");
ve.setApplicationAttribute("class.resource.loader.class",
org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader.class);
ve.init();
Template t = ve.getTemplate("template.html");
每次都失败,除了Velocity的资源加载器找不到该文件之外。
我有两个问题-首先,这是否是配置ClasspathResourceLoader使用的正确方法? 其次,如果配置正确,我将指定什么路径,以便可以在该内部嵌套jar中找到template.html?
经过大量挖掘,我设法找到了答案。
使用ClasspathResourceLoader的代码如下:
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
其次,许多人告诉我,在一个嵌套的jar内,标准的classpath加载器甚至都无法找到template.html
文件。 有人告诉我,一些花哨的第三方类加载器是必要的。 OneJar提供了这种精美的装载机。 一旦我获得正确的代码以使用ClasspathResourceLoader,事情似乎就解决了。
要记住的是“ /”相对于类路径根。 因此,当$base/src/main/resources/template.html
在解压缩的JAR的根目录中重新打包为template.html
时,这意味着/template.html
是要加载的正确资源路径。
该路径/template.html
当然是相对于嵌套内部JAR的。 我不知道类加载器(无论是标准加载器还是OneJar)在外罐和内罐的/
之间如何混淆。
使用/作为相对路径,指定template.html所在的路径
并使用如下的setProperty
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
final String templatePath = "/" + template + ".html";
Template template = ve.getTemplate(templatePath, "UTF-8");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.