Where should I put Velocity template files for a command line utility built with Maven?

爷,独闯天下 提交于 2019-12-14 02:34:06

问题


I have a small command line utility project that I'm using Maven to manage. The utility is a very simple app to populate a Velocity template and dump the results to a new file. My problem is where to put my Velocity templates. When I put them in src/test/resources/foo/bar/baz, mvn test fails because it can't find the referenced template, even though it is clearly there in target/classes/foo/bar/baz, which is where the .class file for the test and the class under test are located. If I put the template in the top-level directory of the project, the test passes, but then I'm not following the Maven project structure, and I suspect that the actual packaged .jar file wouldn't function. What am I missing?

UPDATE:

Method under test:

public final void mergeTemplate(final String templateFileName, final Writer writer) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, Exception {
    Velocity.init();
    Velocity.mergeTemplate(templateFileName, Charset.defaultCharset().name(), context(), writer);
}

Test method:

@Test
public void testMergeTemplate() throws Exception {
    final FooGenerator generator = new FooGenerator();
    final StringWriter writer = new StringWriter();
    generator.mergeTemplate("foo.yaml", writer);
    Assert.assertEquals("Something went horribly, horribly wrong.", EXPECTED_RESULT, writer.toString().trim());
}

The only place I can place foo.yaml and have the tests pass is in the root directory of the project, i.e., as a peer of src and target.


回答1:


You can programmatically configure TEMPLATE_ROOT as follows:

Properties props = new Properties();        
props.put("file.resource.loader.path", templateRootDir);

VelocityEngine engine = new VelocityEngine();
engine.init(props);
engine.evaluate(...);



回答2:


You should put them in src/main/resources/foo/bar/baz because they need to be included in the main jar file.




回答3:


So it turns out that instead of using something like

generator.mergeTemplate("foo.yaml", writer);

I should use something like

InputStream fooStream = getClass().getResourceAsStream("foo.yaml");
generator.mergeTemplate(fooStream, writer);



回答4:


You could just configure Velocity to use the ClasspathResourceLoader, instead of the default FileResourceLoader.




回答5:


I have tried Velocity.setProperty() to set the properties similar to what was said above by @Jin Kim and was able to run it.

VelocityEngine ve = new VelocityEngine();
ve.setProperty(RunTimeConstants.RESOURCE_LOADER,"file");
ve.setProperty("file.resource.loader.path",templaterootdir);

ve.init();


来源:https://stackoverflow.com/questions/435210/where-should-i-put-velocity-template-files-for-a-command-line-utility-built-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!