如何使用maven生成要包含在Jar文件中的资源?

yan*_*kee 4 maven

在构建过程中,我需要由外部工具生成一些文件。对于我的最小可编译示例,我将“外部工具”简化为以下脚本:

mkdir -p target/generated-resources
echo "hello world" > target/generated-resources/myResource.txt
Run Code Online (Sandbox Code Playgroud)

现在我想在构建期间执行外部工具,并且生成的资源应包含在 war 文件中。我找不到任何有关如何完成此操作的文档,因此只是猜测我需要将生成的资源写入target/generated-resources. 那么也许这是一个问题?

我使用以下构建配置创建了一个 pom.xml 文件:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <executable>./createResource.sh</executable>
            </configuration>
        </plugin>
    </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)

如果我运行mvn packagecreateResource.sh 脚本,则会成功执行并创建 myResource.txt 文件。但是,myResource.txt 文件不包含在生成的 .jar 文件中。

我注意到如果我添加它就会起作用

<resources>
  <resource>
    <directory>target/generated-resources</directory>
  </resource>
</resources>
Run Code Online (Sandbox Code Playgroud)

我的构建配置,但我担心如果其他插件可能以不同的方式使用此目录,这可能会导致问题(是吗?我真的找不到有关该target目录约定的任何信息)。

另外,我更喜欢一个与通常的 Maven 约定一起使用的解决方案(如果存在这种情况的约定)。

如何在使用 maven 构建期间正确生成要包含在 jar 文件中的资源?

Tom*_*ome 5

Maven 的约定(或至少主要用途)是在内部生成资源(target/ generated-resources/[plugin/process])。但与生成的源和编译器插件不同,生成的资源不是由 jar 插件专门处理的,因此您必须将其添加为资源(使用像您所做的那样的新资源或 build-helper-plugin)。

如果您遵循惯例将生成的所有内容都放置在 generated-resources 的子目录下,那么您应该不用担心其他插件如何使用它。