Adding Additional Source Folders to Your Maven Build

By

1 minute read time

Occasionally, you need to add additional source folders to your Maven build, usually when you are generating a source via some external method or AntTask. Maven plugins that generate sources are expected to add the source folder automatically, but that's of little consequence if an existing Maven plugin does not support your generation method. Fortunately, there is the build-helper-maven-plugin to assist you.

The usage page gives plenty of examples. Adding an additional source folder is as simple as:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.1</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>

Several threads cited from Inderjeet's blog suggest tweaking the compiler plugin's settings to add the additional source folder. While this will work in simple cases, this method does not actually add an additional sourceFolder element in the project model. This means other plugins, particularly IDE integrations such as M2eclipse, won't see these folders and will cause you trouble down the road. We therefore suggest you use the build-helper instead.

The build-helper lets you do some other handy things, such as attach additional artifacts (attachedArtifacts), purge the project's artifacts from the local repository, and add additional testSource folders.

Picture of Brian Fox

Written by Brian Fox

Brian Fox, CTO and co-founder of Sonatype, is a Governing Board Member for the Open Source Security Foundation (OpenSSF), a Governing Board Member for the Fintech Open Source Foundation (FINOS), a member of the Monetary Authority of Singapore Cyber and Technology Resilience Experts (CTREX) Panel, a ...

Tags