0

What is the best practice for including template group files in a jar?

I would like to include my StringTemplateGroup file in my executable jar. I'm using Eclipse and have put the template group file in a folder called "template" under the project. In my java code, I create the files using:

STGroup File templates = new STGroupFile("template/file.stg");

This works fine in Eclipse, but when I export the jar and run it, I get the following error:

Exception in thread "main" java.lang.IllegalArgumentException: No such group file: template\HasbroServiceHelper.stg

How do I get the name of the file in the jar file itself, so I can prefix with "jar:file" or is there a better way to package the template file in the jar?

  • STGroup File templates = new STGroupFile("/yourpath/template/file.stg"); Have you tried with fully qualified name ? – Devesh Jun 09 '14 at 18:26

2 Answers2

0

I have not tested it, but something like this should work.

String fullPath = getClass().getClassLoader().getResource("/template/file.stg").getFile();  
STGroup File templates = new STGroupFile(fullPath);
0

There are two approaches to do this

  1. In my case I have package the "templates" Folder along with the jar file. Why: so the benefit of doing this if I need to change the template then in that case we don't need to regenerate or redeploy the jar

When we run the above code from the eclipse then eclipse knows that you are running from the project directory. That's the reason its running fine from the eclipse

myapp
 |-- myapp.jar
 |---Templates folder

If you run the jar from the "myapp" folder then you will not get the above exception.

  1. Second Possible way to do this you have to keep your template files in your classpath means move them into resources folder and call it by the ResourceLoader

But in this case if you have some changes in the templates then you have re-build your entire project

@Autowired
 ResourceLoader resourceLoader;
 
  resourceLoader.getResource("classpath:template/mytemplate.stg");

Hope that Helps :)

Siddharth
  • 197
  • 1
  • 14