如何添加一个额外的源目录,以便 maven 编译并包含在构建 jar 中?

除了 src/main/java 之外,我还添加了一个 src/bootstrap 目录,我希望在构建过程中包含它,换句话说,我希望 maven 编译并在构建中包含源代码。怎么会?

177158 次浏览

你可以使用 构建帮助插件,例如:

<project>
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>some directory</source>
...
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

您可以为生成过程添加以下目录:

    ...
<resources>
<resource>
<directory>src/bootstrap</directory>
</resource>
</resources>
...

Src/main/java 是在 pom.xml 中不需要提及的默认路径

注意: 这个解决方案只是将 java 源文件移动到 target/classes 目录,而不会编译源文件。

更新 pom.xml为 -

<project>
....
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
...
</build>
...
</project>

在最近的 Maven 版本(3)和最新版本的 Maven 编译器插件(3.7.0)中,我注意到,如果包含要添加到构建中的源代码的文件夹位于 target文件夹或其子文件夹中,则不需要添加带有 build-helper-maven-plugin的源文件夹。
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
例如,在 target/a中有一些(生成或没有)源代码,target/generated-source/foo将被编译并添加到 outputDirectory: target/classes中。