[英]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.