Sometimes, you might feel the need to add an “extra” source directory in Maven. This becomes tricky specifically when you have already added that extra directory in your favorite IDE. Because of this, you will not see the compiler errors until you build the project using Maven. The need to add the extra source directories becomes more prevalent when you are using some automatic code generation (like Spring query DSL) in your project.
For the sake of covering a wider range of audience and to make this post more helpful, I will begin by considering that the default Maven configuration (only src/main/java and src/test/java added in your IDE).
Consider the below project structure in which only
src/test/java added in source directories in your IDE (eclipse).
Please note that there is a directory named “extra” that is not added as a source directory. Now go ahead and add the directory named “extra” as a source directory in eclipse.
Step 1) Right click on your project> Properties > Java Build Path> Add Folder> select “extra”
Step 2) Once you complete the above step, you should be able to see the recently added directory added as the source directory.
Step 3) However, doing so, the compilation errors in eclipse will be kicked out, however, you won’t be able to build this project using Maven. If you try to do so, you’ll get the below error.
[INFO] 2 errors
[INFO] BUILD FAILURE
[INFO] Total time: 2.321 s
[INFO] Finished at: 2016-10-02T20:14:55+05:30
[INFO] Final Memory: 14M/161M
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project multisrc: Compilation failure: Compilation failure:
[ERROR] /D:/eclipse/Workspaces/luna-ws/websandbox/multisrc/src/main/java/org/websandbox/multisrc/App.java:[3,27] package some.other.packages does not exist
[ERROR] /D:/eclipse/Workspaces/luna-ws/websandbox/multisrc/src/main/java/org/websandbox/multisrc/App.java:[15,9] cannot find symbol
[ERROR] symbol: variable ExtraSourceFile
[ERROR] location: class org.websandbox.multisrc.App
Step 4) Add the Maven plugin to include the extra source directory in your build.
Step 5) Build your project and everything should be fine now. Download this project example from GitHub.
You might see the below error in your pom.xml once you add the plugin mentioned above.
Don’t worry, just click “Discover new m2e connectors” and follow the steps.
Read more about the plugin usage here.