I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Introduction

We sometimes need to use multiple source directories in a Java project. A common case example when there are classes that are generated automatically and placed in a different directory.

In this short article, we’ll show how to set up Maven to work with additional source directories.

2. Adding Another Source Directory

Assuming we have a Maven project already created, let’s add a new source directory called another-src in the src/main folder.

After that, let’s create a simple Java class inside this folder:

public class Foo {
    public static String foo() {
        return "foo";
    }
}

Let’s now create another class in our src/main/java directory that uses the Foo class we’ve just created:

public class MultipleSrcFolders {
    public static void callFoo() {
        Foo.foo();
    }    
}

Our project structure now looks like this:

If we try to compile this project with Maven we get a compilation error because the Foo class is not included in the project:

[ERROR] .../MultipleSrcFolders.java:[6,9] cannot find symbol
[ERROR]   symbol:   variable Foo
[ERROR]   location: class com.baeldung.maven.plugins.MultipleSrcFolders

3. Using the Builder Helper Plugin

With Maven, we can use the Builder Helper plugin to add more source directories. This plugin lets us customize the build lifecycle in different ways.

One of its goals is the add-sources, which is intended to add more src directories to the project during the generate-sources phase.

We can use it in our project by adding it to our pom.xml:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/main/another-src</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

The latest version of the plugin can be found in Maven Central.

If we compile now our project, the build succeeds.

4. Conclusion

We’ve seen in this article how to set up the Builder Helper Maven plugin to work with multiple src directories in a Maven project.

As always, the full source code of the examples is available over on GitHub.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS