Adding additional source folders to your Maven build


May 22, 2008 By Brian Fox

Occasionally you have a need to add additional source folders to your Maven build, usually when you are generating 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 your generation method is not supported by an existing Maven plugin. 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 includes 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 that 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.