Lesson · Build Tools & Project Structure
Build tools and the project structure they assume
11 min readBuild Tools & Project Structure
Before Maven or Gradle runs a single task, both assume the same directory layout. This lesson covers that contract, the two tools that read it, and the dependency discipline that keeps a growing project buildable.
The layout is the contract
A Java project is a directory tree with names so standard that every tool already knows them. The compiler does not care where your sources live, but every build tool, IDE, test runner and CI recipe does. Drop a Maven or Gradle project into any of them and it runs; invent your own layout and every consumer needs to be taught.
The standard tree: src/main/java holds production sources, src/main/resources holds files that go on the classpath, src/test/java holds test sources, and one output directory collects everything a build produces, target/ for Maven and build/ for Gradle. The two names mean the same thing, and both are disposable: deleting them and rebuilding must produce the same result.
Inside src, one rule is stricter than a convention. A package must match its directory, so com.acme.report.CsvExporter lives at src/main/java/com/acme/report/CsvExporter.java, because javac resolves it that way. Get it wrong and the compiler either cannot find the class or quietly builds a package the file refuses to admit it belongs to.
my-app/ pom.xml or build.gradle.kts the build description src/main/java/... compiled for production src/main/resources/... copied onto the classpath src/test/java/... compiled for the test tasks target/ or build/ disposable output
Convention over configuration is not laziness, it is amortised onboarding. Every tool you will ever add to this project already knows this tree.
Maven: one POM, one lifecycle, bindings everywhere
Maven describes a project in a single file, pom.xml, the Project Object Model. The project is identified by coordinates: groupId, artifactId and version, which together name it in every repository. com.acme:payments:2.4.0 is a coordinate, not a folder; the repository turns it into a path.
The interesting part is not the XML, it is the lifecycle: a fixed sequence of phases, and plugins that attach goals to those phases. mvn package does not run one program; it walks every phase up to package and executes whatever goals are bound to each one. That is why the same command tests, compiles and packages in one go.
| Phase | Typical binding | You type |
|---|---|---|
| validate | the POM is checked for completeness and consistency | mvn validate |
| compile | maven-compiler-plugin:compile | mvn compile |
| test | surefire:test runs unit tests | mvn test |
| package | jar:jar writes target/app-1.0.jar | mvn package |
| verify | failsafe integration tests and other checks | mvn verify |
| install | the artifact is copied into the local repository | mvn install |
| deploy | the artifact is uploaded to a remote repository | mvn deploy |
- A plugin defines goals; the POM binds a goal to a phase. A plugin that is declared but not bound to anything changes nothing about the build.
- Packaging implies default bindings. Type
<packaging>jar</packaging>and Maven already binds compiler, surefire and jar to the right phases, which is why a minimal POM still produces a working build. - A goal can also be run directly (
mvn surefire:test), bypassing the lifecycle. That is fine in a shell and invisible in CI, so anything a pipeline depends on belongs in a binding, not in someone's history.
Know the phases and the commands stop being magic. mvn verify means every phase below verify has already run, and every goal bound to those phases ran with it.
Dependencies: scopes, caches and the mediation rule
A dependency has a scope, and the scope decides where the dependency is visible, who inherits it, and whether it ends up inside the artifact.
The other half of the story is where dependencies come from. A build resolves them from remote repositories against a local cache: ~/.m2/repository for Maven, ~/.gradle/caches/modules-2 for Gradle. The first build pays the network cost, later builds read the cache, and CI starts cold every time unless the cache is carried between runs.
Transitive dependencies are the feature that makes a resolver worth having. Depend on one library and you depend on everything it needs. Conflicts are settled by strategy: Maven uses nearest wins, where the shallowest path in the tree supplies the version and ties break by declaration order, while Gradle selects the newest requested version by default.
Do not fix a conflict by editing one declaration. A version typed into a leaf moves every path that passes through it, which is how one line changes the behaviour of three libraries. Control belongs one level up: dependencyManagement in Maven, with <scope>import</scope> for a BOM, and platform(...) or enforcedPlatform(...) in Gradle.
| Scope | Compile classpath | Test classpath | Packaged | Use for |
|---|---|---|---|---|
| compile (default) | yes | yes | yes | libraries the application calls to do its work |
| provided | yes | yes | no | APIs the runtime supplies, such as a servlet container's API |
| runtime | no | yes | yes | implementations selected at run time, such as a JDBC driver |
| test | no | yes | no | JUnit, Mockito, fixtures |
Versions belong to the platform, not to the leaf. Pin the family once, and every transitive path resolves through the same version.
Gradle: a task graph in a script
Gradle starts from the same layout and the same job, but its build script is a program in Kotlin (or Groovy) and its model is a task graph. Plugins register tasks with declared inputs and outputs; gradlew build runs whatever the graph says, in an order the graph allows, in parallel where it can.
Declared inputs and outputs are also why Gradle can skip work. A task whose inputs, outputs and implementation are unchanged is reported UP-TO-DATE instead of running again, and with the build cache enabled it can be FROM-CACHE even on another machine. That only holds if your custom tasks describe their inputs and outputs honestly: a task that reads a file it never declared either runs forever or, worse, does not run when it should.
- Kotlin DSL is the modern default: since Gradle 8.2,
gradle initgenerates Kotlin scripts for new projects, and type-safe accessors give IDE completion inside the build file itself. - Version catalogs (stable since Gradle 7.4) keep versions in one
libs.versions.tomlundergradle/, so scripts saylibs.jackson.databindand an upgrade is a one-line diff. - Builds are code, and code deserves structure: a convention plugin in
buildSrcor abuild-logicbuild stops fifteen subprojects from each repeating the same configuration block.
Build board · one layout, four stations
pick a stationthe idea
Both tools assume the same tree before they are told anything: production sources in src/main/java, resources on the classpath from src/main/resources, tests in src/test/java, output in target/ or build/. Zero configuration works because the names are the configuration.
the trap
Putting sources anywhere else forces every tool to be told where things are. That is one setting in the build, one in the IDE, and one in the CI recipe, each of which can drift.
Maven and Gradle, side by side
The two tools are more alike than the arguments suggest. Both use the standard layout, both resolve from repositories into a local cache, both ship a wrapper, and both can run tests, static analysis and packaging in one command. The differences are in the centre of gravity.
| Aspect | Maven | Gradle | Why it matters |
|---|---|---|---|
| Build description | pom.xml, declarative XML | build.gradle.kts, a script | Declarative reads easily; a script bends to unusual needs without a plugin. |
| Model | a lifecycle of phases | a directed graph of tasks | Phases are predictable; graphs let independent work run in parallel and be skipped. |
| Extending | write a plugin, bind goals to phases | apply a plugin, configure tasks directly | Gradle puts the extension point within the build author's reach. |
| Incremental builds | mostly whole phases; plugin dependent | first-class per task, with a shared cache | The payoff grows with the project and the CI bill. |
| Version control | BOM plus dependencyManagement | version catalog plus platforms | Same discipline, different syntax. |
| Adoption | ubiquitous and deliberately boring | the default for new JVM and Android builds | Boring is a feature in build infrastructure; a familiar default is a feature for hiring. |
Pick one, commit the wrapper, keep versions in one place. Most build pain is not the tool; it is four versions of a library declared in three files that two people own.
Wrappers, lockfiles and verification
Reproducibility has two halves: the build tool and the dependencies. The wrapper covers the first. mvnw and mvnw.cmd, or gradlew and gradlew.bat, are committed to version control and download a pinned tool version, so every developer and every CI runner uses the version recorded in the wrapper properties rather than whatever is installed on the machine.
The second half is resolution. Gradle can write a lockfile, recording the resolved version of every dependency, and both tools can verify downloads: Gradle's dependency verification checks checksums and signatures against a metadata file you commit. A lockfile plus verification turns "it resolved on my machine" into a reviewable diff, which is exactly what supply chain review needs.
- Never run a globally installed maven or gradle against project work. The wrapper is the project's pin, and CI should call it in the same form you do.
- Upgrade deliberately: change the wrapper properties (or run the wrapper task), commit the diff, and let the team review which tool version moved.
- The wrapper pins the tool, not the JDK. The JDK comes from JAVA_HOME or a toolchain declaration, and installing-java covers why a wrong JAVA_HOME breaks builds while
javastill works in your shell.
The wrapper command is the only build command that means anything. If a build works on your laptop and fails in CI, first check which tool each side actually executed.
Quality gates inside the build
A build is the one place every change must pass through, which makes it the right place for the checks nobody should have to remember. The standard cast, one line each:
- SpotBugs reads compiled bytecode and flags bug patterns a compiler accepts, such as ignored return values and broken equals contracts.
- Checkstyle enforces declared style rules as a build failure instead of a review comment.
- Error Prone plugs into
javacand fails the compilation on suspicious code, which makes it the strictest of the three because nothing slips past it unnoticed. - Spotless formats code with a team formatter such as google-java-format, which ends the whitespace debate by automating it.
- Javadoc generation is a build goal too.
mvn javadoc:javadocor thejavadoctask fails the build on a broken doc comment, long before a release tries to publish it. - Annotation processing is a build step, not a runtime trick.
javacruns processors from the processor path and compiles the generated sources in the same run; consuming-annotations covers the processors themselves, the build only has to wire them in.
A rule that cannot fail the build is a suggestion. Put the cheap checks where every change must pass.
Multi-module builds and repository hygiene
Multi-module builds are where layout and dependency discipline pay off. Maven has an aggregator POM listing <modules>, and Gradle has include("app") lines in settings.gradle.kts. Each module then keeps the standard layout and declares only what it uses, and the build orders itself from those declarations. Never enforce build order by scripting it; that is the graph's job.
Repository hygiene is part of the same contract. Output directories, tool caches, IDE files and jars downloaded by hand never belong in commits, because they are either reproducible (target/, build/) or specific to one machine (.idea/, *.iml).
- Ignore build output:
target/andbuild/are regenerated, never committed. - Ignore tool state:
.gradle/and the wrapper's local download state. - Ignore IDE files:
.idea/,*.iml,.classpath,.project,.settings/, and.vscode/unless the team agrees on shared files. - Ignore loose artifacts: a
*.jarsomeone built or downloaded, with one exception: the Gradle wrapper jar IS committed, because the wrapper is how the pinned tool version travels.
If a clean checkout plus the committed wrapper cannot rebuild it, it was never in version control. Treat that as a bug report about the repository, not the code.
Build anatomy · the tree feeds the stations
one layout, two sets of names for the same steps
the tree every tool assumes
Inside src, the harder rule: a package must match its directory, so the compiler and the build agree on every class name.
the pipeline, station by station
every source file first, then resources onto the classpath
unit tests run before any artifact exists
the jar lands in target/ or build/libs/
checks that need a built artifact come last
Running a named station runs every station before it, which is why one command compiles, tests and packages in one pass.
What to keep
The sequence that keeps builds boring: keep the standard layout, let a BOM or a catalog own the versions, run tests and static analysis inside the same lifecycle you use to release, and commit the wrapper so everyone runs the same build. The tools disagree about syntax; they do not disagree about any of that.
The layout is the contract; the build tool is just the first thing that reads it. Learn the contract once and every build file afterwards is spelling.
The conflict that was fixed in one place
A transitive dependency pulls in an old version of a library, so someone adds a version to the direct declaration and the build goes green. What actually happened: every path that reached that library now resolves to the new version, including the two dependencies whose maintainers tested against the old one. The failure, when it arrives, is in code nobody edited. Fix versions at the family level instead: a BOM import or dependencyManagement in Maven, a platform in Gradle, and a lockfile to make the resolution visible in review.
Interview angles
What does the standard project layout buy you?+
Tools find things without being told. Maven and Gradle compile from src/main/java into target/ or build/, the IDE and the test runner agree on src/test/java, and a new teammate spends the first day on the domain instead of the directory tree. The layout is the interface between your project and every tool that will ever touch it.
The one hard rule inside it is package equals directory: javac resolves com.acme.report.CsvExporter to src/main/java/com/acme/report/CsvExporter.java. Every other part of the layout is convention, but a convention that four tools already implement.
Walk the Maven lifecycle and explain what mvn verify actually does.+
validate, compile, test, package, verify, install, deploy. Each command runs every phase up to the named one, and plugins run whatever goals are bound to those phases. mvn verify therefore compiles, runs unit tests, packages the jar, and runs the checks bound to verify, such as failsafe integration tests.
Common misconception: That typing a goal like mvn surefire:test runs the lifecycle. It does not: it runs that one goal in isolation, which is why a build that depends on command-line goals breaks the moment CI runs the lifecycle instead.
How do Maven and Gradle settle a version conflict?+
Maven applies nearest wins: the version from the shallowest path in the dependency tree is chosen, with ties broken by declaration order. Gradle selects the newest requested version by default. Both allow explicit control: dependencyManagement with an imported BOM in Maven, platforms and constraints in Gradle.
Control matters because both defaults are heuristics. Nearest wins can pick an older version from a direct dependency over a newer one deeper in the tree, and newest-wins can drag a library forward past what its consumer supports. The fix is to decide the version once, centrally, and let every path resolve through it.
Why commit the build wrapper?+
The wrapper is a pinned tool version in version control. Everyone who checks out the project runs the same Maven or Gradle, CI included, without depending on what is installed on the machine. It also makes upgrading the tool a reviewable diff rather than an invisible local change.
Follow-up: And the dependencies themselves? A lockfile records the resolved version of every artifact, and dependency verification checks checksums and signatures, so a modified or substituted artifact fails the build instead of shipping.