以前就遇到过在linux上和在windows上获取文件路径的方式不一样;因为我平常在windows上开发项目,最后部署到docker容器中就会报无法找到模板路径;我在windows本地是以springboot项目启动,部署到docker中是以jar包方式启动,可见这两种方式会影响模板路径的获取。
这次的问题跟以前稍微不一样,都是部署在docker中,以前是war包运行,现在改成jar包运行,也是报org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource
1. tomcat项目war包部署运行获取方式如下:
VelocityEngine velocityEngine = new VelocityEngine();
Properties properties = new Properties();
String dir = MailSendService.class.getResource("/").getPath();
String path = "static/template";
Sring name = "test.vm";
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, dir + path);
velocityEngine.init(properties);
Template template = velocityEngine.getTemplate(name, "utf-8");
模板文件一般存放在resource目录下的static/template文件夹下,war包运行中这么获取是没问题的,把项目变成jar包部署运行就报错了;所以修改代码如下:
2.jar包中获取方式
VelocityEngine velocityEngine = new VelocityEngine();
Properties properties = new Properties();
properties.setProperty("resource.loader", "class");
properties.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocityEngine.init(properties);
String path = "static/template";
Sring name = "test.vm";
Template template = velocityEngine.getTemplate(path + name, "utf-8");