Let's introduce the two main characters of this article:
Apache Maven-Just Red project management tool
Freemarker-Veteran template engine
What is the conflict between the two seemingly irrelevant?
Maven has a built-in resource substitution mechanism that can be used for variable substitution of resource files managed by Maven. Pre-defined MAVEN attribute variables include ${name},${project.version},${project.packaging} , and ${ Project.artifactid} and so on. Students familiar with Freemarker will find that Maven uses the same method as Freemarker to define variables:${variable name}.
If you place the Freemarker template file in the Maven resource file directory (for example, src/main/resources), in the default configuration, The MAVEN Packaging tool scans these freemarker template files and replaces all of the Maven-recognizable variables.
For example, there are the following Freemarker template code
< tr > < TD class = "label" > Name:</ TD > < TD > My Maven project</ td > </ tr >
The ${name} variable should be a Freemarker variable, replaced by the Freemarker engine at run time, but ${name} is also a MAVEN predefined variable that, when the MAVEN project is packaged, The variable is replaced with the corresponding MAVEN attribute value and written to the packaged file, and the template in the final packaged file looks like the following.
<tr> <td class= "label" >Name:</td> <td>my Maven project</td></tr>
There are two workarounds, which is simply to avoid using the MAVEN attribute variable name in the Freemarker template, such as replacing ${name} with ${customername}, so maven will not modify the file.
A better approach is to declare a direct copy of the Freemarker template file in the Maven pom file without any maven resource substitution. As the following example shows, two pairs of filter rules are defined, the first rule declares that the Freemarker template file should not be replaced by a resource, and the second rule declares a direct copy of the Freemarker template file.
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ftl</include>
<include>**/*.tpl</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ftl</include>
<include>**/*.tpl</include>
</includes>
</resource>
</resources>
Note: Without a second rule, the Freemarker template file will not be copied to the final packaged file.
161213. Maven resource substitution and Freemarker templates