过滤

变量可以包含在您的资源中。这些由${...}分隔符表示的变量可以来自系统属性、项目属性、过滤器资源和命令行。

例如,如果我们有一个资源src/main/resources/hello.txt包含

Hello ${name}

像这样的POM

<project>
  ...
  <name>My Resources Plugin Practice Project</name>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
      ...
    </resources>
    ...
  </build>
  ...
</project>

调用时

mvn resources:resources

这将在target/classes/hello.txt中创建一个包含完全相同文本的资源输出。

Hello ${name}

但是,如果我们向 POM 添加一个<filtering>标记并将其设置为true,如下所示:

      ...
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
      ...

我们调用后的target/classes/hello.txt

mvn resources:resources

将是

Hello My Resources Plugin Practice Project

这是因为 name 变量被项目名称的值(在 POM 中指定)替换。

此外,我们还可以使用“-D”选项通过命令行赋值。例如,要将变量名称的值更改为“world”,我们可以简单地调用以下命令:

mvn resources:resources -Dname="world"

target/classes/hello.txt中的输出将是

Hello world

此外,我们不限于使用预定义的项目变量。我们可以在<properties>元素中指定我们自己的变量及其值。例如,如果我们想将变量从“name”更改为“your.name”,我们可以通过在<properties>元素中添加<your.name>元素来实现。

<project>
  ...
  <properties>
    <your.name>world</your.name>
  </properties>
  ...
</project>

但是为了组织您的项目,您可能希望将所有变量及其值放在一个单独的文件中,这样您就不必重写您的 POM,或者在每次构建时一直设置它们的值。这可以通过添加过滤器来完成。

<project>
  ...
  <name>My Resources Plugin Practice Project</name>
  ...
  <build>
    ...
    <filters>
      <filter>[a filter property]</filter>
    </filters>
    ...
  </build>
  ...
</project>

例如,我们可以通过指定过滤器文件my-filter-values.properties将“your.name”与 POM 分开,其中包含:

your.name = world

并将其添加到我们的 POM

    ...
    <filters>
      <filter>my-filter-values.properties</filter>
    </filters>
    ...

Warning: Do not filter files with binary content like images! This will most likely result in corrupt output.

If you have both text files and binary files as resources it is recommended to have two separated folders. One folder src/main/resources (default) for the resources which are not filtered and another folder src/main/resources-filtered for the resources which are filtered.

<project>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources-filtered</directory>
        <filtering>true</filtering>
      </resource>
      ...
    </resources>
    ...
  </build>
  ...
</project>

现在您可以将这些文件放入不应过滤的src/main/resources中,将其他文件放入src/main/resources-filtered中。

如前所述,过滤图像、pdf 等二进制文件可能会导致输出损坏。为了防止此类问题,您可以配置不会被过滤的文件扩展名。