问题
Let me clarify my current practice. I have a maven project and the package architecture looks like below:
src/main/java/com/gearon/app/App.java
src/main/java/com/gearon/app/configuration/Config.java
src/main/java/com/gearon/app/datamodel/*.java
I tried to set directory where to load templates in Config.java with code below:
cfg = new Configuration();
cfg.setClassForTemplateLoading(Config.class, "/templates");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
I have put templates under src/main/java/com/gearon/app/templates
The architecture is src/main/java/com/gearon/app/templates/*.ftl
It works fine if I run the code directly with main method. However, when I package the project into a jar, it fails to load templates and the error looks like below:
java.io.FileNotFoundException: Template "index.ftl" not found.
I'd like to know where to put those tempaltes.
回答1:
Hmmm, based on research on manual from Freemarker official site
void setClassForTemplateLoading(Class cl, String basePackagePath) and void setClassLoaderForTemplateLoading(ClassLoader classLoader, String basePackagePath): These are for when you want to load templates via the same mechanism with which Java loads classes (from the class-path, as they used to say vaguely). This is very likely be the preferred means of loading templates for production code, as it allows you to keep everything inside the deployment jar files. The first parameter decides which Java ClassLoader will be used. The second parameter specifies the package that contains the templates, in /-separated format. Note that if you don't start it with /, it will be interpreted relatively to the package of the Class parameter.
The Note is what matters:
Note that if you don't start it with /, it will be interpreted relatively to the package of the Class parameter.
After changecfg.setClassForTemplateLoading(Config.class, "/templates");
tocfg.setClassForTemplateLoading(Config.class, "templates");
Everything works fine like a charm.
来源:https://stackoverflow.com/questions/50478337/where-does-freemarker-load-templates-in-a-maven-generated-jar