1. Overview
By default, Maven uses the /project-path/src/main/java directory as the only source directory. However, in some cases, we need to define additional source directories. In this quick tutorial, we're going to look at how we can add multiple source directories in a Maven-based Java project.
2. Add Source Directory with Build Helper Maven Plugin
We'll use the Build Helper Maven plugin to register additional source directories.
Assume that we have a sibling directory next to the src folder. Now we'll register it as the second source directory:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>imported/main/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Here, we're running the add-source goal in the generate-sources phase. Remember that Maven default lifecycle contains the following phases until compilation: validate, initialize, generate-sources, process-sources, generate-resources, process-resources and compile. So we're registering the new source directory before Maven processes and compiles the source code. Then we're specifying the source directory in a configuration.sources.source element. Although we've added a single directory, we can also add more.
3. Add Test Source Directory with Build Helper Maven Plugin
Now we'll add a test source directory using a similar configuration:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-test-source</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>imported/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
In this configuration, we're using the add-test-source goal instead of add-source. Moreover, we're specifying the phase as generate-test-sources. After compiling the source code, Maven uses the following phases to compile the test sources: generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, and test-compile. So Maven includes the new directory for compiling the tests.
4. Summary
In this tutorial, we've learned how we can add multiple source directories using the Build Helper Maven plugin.
As always, the source code is available on Github.