Where should I put Velocity template files for a c

2019-08-08 06:12发布

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.

5条回答
神经病院院长
2楼-- · 2019-08-08 06:51

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();
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-08 06:53

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

查看更多
太酷不给撩
4楼-- · 2019-08-08 06:59

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

查看更多
相关推荐>>
5楼-- · 2019-08-08 07:00

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);
查看更多
你好瞎i
6楼-- · 2019-08-08 07:04

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(...);
查看更多
登录 后发表回答