Skip to content
notes.vinhnq.com

Search

Git, DevOps & ToolingJunior19 min read

Maven and the layout of a Spring Boot project

Review 16 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

Open a Spring Boot project and the first things you meet are pom.xml, mvnw and a fixed folder tree. This post explains what Maven does with them: download libraries, pick versions, run the build steps and package one runnable jar. Afterwards you can read a POM, fix download errors and answer the usual build questions in interviews.

At a glance:

flowchart LR
  A["pom.xml: GAV coordinates"] --> B["Parent/BOM manages versions"]
  B --> C["Dependencies, scope, transitive"]
  C --> D{"In ~/.m2?"}
  D -->|"No"| E["Download from Maven Central"]
  D -->|"Yes"| F["Lifecycle: compile, test, package"]
  E --> F
  F --> G["Fat jar: java -jar"]

1. What Maven solves

Key idea: Maven is a build tool: it downloads libraries, compiles, runs tests and packages along a standard process, so anyone who clones the project builds the same result.

Without a build tool you download each jar yourself, assemble the classpath (the list of places the JVM looks for classes) and type javac by hand. Maven replaces that with three conventions:

  • Declare, don’t script: you write “I need library X version Y” in the POM, Maven finds and downloads it.
  • A standard layout: code in src/main/java, tests in src/test/java. No paths to configure.
  • A standard lifecycle: mvn package means the same thing in every project.

Maven is not a documentation site for libraries. It only fetches them from a repository (a store of jars and POMs), Maven Central by default.

2. The POM and GAV coordinates

Key idea: pom.xml (Project Object Model) declares who the project is, which libraries it uses and how it is built. Every artifact is uniquely identified by groupId, artifactId and version.

The POM plays the role of Node’s package.json. The three identity fields:

Field Meaning Example
groupId the organisation, as a reversed domain name com.example
artifactId the project or module name shop
version the version; the -SNAPSHOT suffix marks a work-in-progress build that may change 0.0.1-SNAPSHOT

In a repository the coordinates become a path: com/example/shop/0.0.1-SNAPSHOT/shop-0.0.1-SNAPSHOT.jar. So changing the groupId changes the library’s “address”, as with MySQL in section 5.

The lab’s POM, part by part

The POM of the lab project used in this series (Spring Boot 3.5.9, Java 21), trimmed:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>                                   <!-- inherit Boot's configuration and version table -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.9</version>
    <relativePath/>                          <!-- resolve the parent from the repository, not ../ -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>shop</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>21</java.version>          <!-- the parent uses it to set maven.compiler.release -->
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>   <!-- no <version> -->
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>
    <!-- thymeleaf, validation, security, data-jpa, spring-session-jdbc, test... -->
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <annotationProcessorPaths>          <!-- generates the Product_ metamodel for Specifications -->
            <path>
              <groupId>org.hibernate.orm</groupId>
              <artifactId>hibernate-jpamodelgen</artifactId>
              <version>${hibernate.version}</version>   <!-- reuse Boot's property -->
            </path>
          </annotationProcessorPaths>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>  <!-- builds the fat jar -->
      </plugin>
    </plugins>
  </build>
</project>

${hibernate.version} is a property defined by the parent. Check its real value with mvn help:evaluate -Dexpression=hibernate.version -q -DforceStdout; the lab prints 6.6.39.Final. Since Hibernate 6.3 the processor also has a new name, hibernate-processor; the old name still resolves.

3. Lifecycle, phases and goals

Key idea: the lifecycle is an ordered chain of phases (validate → compile → test → package → verify → install → deploy). Calling a phase runs every phase before it; what each phase does comes from the plugin goals bound to it.

  • Phase: an abstract step, e.g. package = “package it”.
  • Goal: one concrete task of a plugin, written plugin:goal, e.g. compiler:compile, surefire:test.
  • Binding: the jar packaging binds default goals to phases. Adding a plugin binds more goals.

Real output of mvn package on the lab (each --- line is a goal being run):

--- resources:3.3.1:resources (default-resources) @ shop ---
--- compiler:3.14.1:compile (default-compile) @ shop ---
--- resources:3.3.1:testResources (default-testResources) @ shop ---
--- compiler:3.14.1:testCompile (default-testCompile) @ shop ---
--- surefire:3.5.4:test (default-test) @ shop ---
--- jar:3.4.2:jar (default-jar) @ shop ---
--- spring-boot:3.5.9:repackage (repackage) @ shop ---

The last goal belongs to spring-boot-maven-plugin: it repackages the plain jar into a fat jar (section 8).

4. Dependencies: scopes and transitive dependencies

Key idea: the scope says at which stage a library is needed. The libraries you declare pull in their own libraries (transitive); mvn dependency:tree shows the whole tree and who brought what.

Scope On compile classpath In tests In the runnable jar Example
compile (default) yes yes yes spring-boot-starter-web
runtime no yes yes JDBC drivers, h2
test no (test code only) yes no spring-boot-starter-test
provided yes yes no, the runtime provides it the servlet API when deploying a war to an external Tomcat

A JDBC driver in runtime scope is right: your code only uses the javax.sql.DataSource interface and never calls MySQL classes, so nobody can import them by accident.

The lab declares 9 dependencies, but mvn dependency:tree prints 105 lines. Filtering a few libraries shows where they come from:

$ mvn dependency:tree -Dincludes=org.hibernate.orm,org.springframework:spring-webmvc,\
    org.hibernate.validator,org.apache.tomcat.embed:tomcat-embed-core
+- org.springframework.boot:spring-boot-starter-web:jar:3.5.9:compile
|  +- org.springframework.boot:spring-boot-starter-tomcat:jar:3.5.9:compile
|  |  \- org.apache.tomcat.embed:tomcat-embed-core:jar:10.1.50:compile
|  \- org.springframework:spring-webmvc:jar:6.2.15:compile
+- org.springframework.boot:spring-boot-starter-validation:jar:3.5.9:compile
|  \- org.hibernate.validator:hibernate-validator:jar:8.0.3.Final:compile
\- org.springframework.boot:spring-boot-starter-data-jpa:jar:3.5.9:compile
   \- org.hibernate.orm:hibernate-core:jar:6.6.39.Final:compile

When two versions of the same library appear in the tree, Maven picks the one nearest the root (nearest wins), and on a tie the one declared first. This rule often causes NoSuchMethodError when an old library drags in a lower version.

Resolving version conflicts: exclusions, dependencyManagement and the enforcer

Three tools, in the order you should reach for them:

  1. dependencyManagement: forces one version for the whole tree, transitive ones included. This is what the starter parent does (section 5).
  2. <exclusions>: cuts an unwanted transitive branch, e.g. drop Tomcat to use Jetty:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
  1. maven-enforcer-plugin with the dependencyConvergence rule: the build fails as soon as the tree contains two different versions of one library, instead of failing at runtime.

Handy commands: mvn dependency:tree -Dverbose (also shows branches omitted as duplicates), mvn dependency:analyze (declared but unused, or used but undeclared).

5. Starter parent, BOM and starters

Key idea: Spring Boot has already chosen a set of versions that work together. The parent or the BOM puts that table into dependencyManagement, so you declare libraries without versions. A starter is a themed bundle of dependencies.

  • dependencyManagement: a table of “if anyone uses library X, use version Y”. It doesn’t add any library to the project.
  • BOM (bill of materials): a POM that only contains dependencyManagement, meant to be imported. spring-boot-dependencies is Boot’s BOM.
  • spring-boot-starter-parent: inherits that BOM and adds plugin configuration (UTF-8 encoding, java.version, resource filtering, repackage).
  • Starter: spring-boot-starter-web = Spring MVC + Jackson + embedded Tomcat. You pick features, not individual jars.

If your company project already has its own parent, you can’t inherit the starter parent; import the BOM instead:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-dependencies</artifactId>
      <version>3.5.9</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

6. The Maven wrapper and ~/.m2

Key idea: mvnw downloads and runs the exact Maven version the project needs, so you don’t install Maven. Downloaded libraries live in ~/.m2/repository and are reused; when one download breaks, delete only that folder.

  • mvnw (a shell script for macOS and Linux) and mvnw.cmd (Windows) read .mvn/wrapper/maven-wrapper.properties for the Maven version and download it into ~/.m2/wrapper the first time. CI and every developer machine use the same Maven.
  • ~/.m2/repository: the local cache, laid out by GAV. The second build downloads nothing; rebuilding the lab with -o (offline) took 1.6 seconds.
  • ~/.m2/settings.xml: per-machine configuration: mirrors, proxies, credentials for internal repositories. Don’t commit it to the project; it often holds passwords.

The usual failure: the network drops mid-download, Maven leaves *.lastUpdated files or a half-written jar, and later builds say “could not resolve” or “invalid LOC header”. Fix it in this order:

  1. ./mvnw -U clean package: -U forces a re-check of artifacts that previously failed.
  2. Delete just the broken folder, e.g. rm -rf ~/.m2/repository/com/mysql/mysql-connector-j/9.5.0, or every *.lastUpdated file.
  3. If the network blocks Maven Central (corporate proxy, firewall), configure a proxy or a mirror in settings.xml.
Mirrors and internal repositories in settings.xml

A mirror is a replacement address for a repository: when Maven wants to download from central, it goes to the mirror instead. In companies the mirror is usually an internal repository (Nexus, Artifactory) that both caches and controls which libraries may be used.

<!-- ~/.m2/settings.xml -->
<settings>
  <mirrors>
    <mirror>
      <id>company-nexus</id>
      <mirrorOf>central</mirrorOf>          <!-- "*" = every repository -->
      <url>https://nexus.example.dev/repository/maven-public/</url>
    </mirror>
  </mirrors>
  <servers>
    <server>
      <id>company-nexus</id>                 <!-- same id as the mirror -->
      <username>${env.NEXUS_USER}</username>
      <password>${env.NEXUS_TOKEN}</password>
    </server>
  </servers>
</settings>

7. The layout of a Spring Boot project

Key idea: code lives in src/main/java, resources in src/main/resources, tests in src/test/java; everything generated goes into target/, which is never committed. Spring Boot adds its own conventions: static/ for static files, templates/ for views, application.properties for configuration.

shop/
├── pom.xml, mvnw, mvnw.cmd, .mvn/wrapper/
├── src/main/java/com/example/shop/
│   ├── ShopApplication.java          # @SpringBootApplication: root of the component scan
│   ├── domain/  repo/  service/  web/  security/  storage/
├── src/main/resources/
│   ├── application.properties        # configuration
│   ├── templates/                    # Thymeleaf views (rendered on the server)
│   └── static/                       # css, js, images: served as is
├── src/test/java/...                 # tests, same packages as the code
└── target/                           # classes/, generated-sources/, *.jar (generated)

A few points people get wrong:

  • The @SpringBootApplication class must sit in the root package: the component scan (the search for beans) only covers its package and sub-packages. Put it in com.example.shop.web and service/ is never scanned. Beans themselves are covered in IoC and DI.
  • target/ is not “what the JVM runs”, as the material says. It is the output folder: classes/ (bytecode plus copied resources), generated-sources/ (e.g. the Product_ class from the annotation processor), the final jar. The JVM runs classes from the classpath; the IDE points that classpath at target/classes.
  • static/ is public: anyone can download its files by URL. Never put configuration or user data there.
  • JSPs don’t go in resources/ but in src/main/webapp/WEB-INF/, and only work with war packaging (part 2).

Packaging by layer (web, service, repo) versus by feature (cart, order) is discussed in DDD and package structure.

8. Fat jar, jar or war, and DevTools

Key idea: spring-boot-maven-plugin packs your code, every library and a launcher into one jar you run with java -jar. Tomcat is inside it, so there is no server to install.

Real numbers from the lab after mvn package:

File Size Content
shop-0.0.1-SNAPSHOT.jar.original 64 KB only my code and resources
shop-0.0.1-SNAPSHOT.jar 58 MB plus 68 library jars in BOOT-INF/lib/ and the launcher
$ unzip -p target/shop-0.0.1-SNAPSHOT.jar META-INF/MANIFEST.MF
Main-Class: org.springframework.boot.loader.launch.JarLauncher
Start-Class: com.example.shop.ShopApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Layers-Index: BOOT-INF/layers.idx

java -jar starts JarLauncher; the launcher builds a class loader that can read jars nested in the jar, and only then calls ShopApplication.main. layers.idx splits the jar into layers (rarely changing libraries, often changing code) so Docker image builds can reuse their cache. A Dockerfile that splits the fat jar into layers, so a code change pushes only a few KB, is in Docker for Spring Boot.

jar or war: a standalone jar is the default and fits containers. You need a war only to deploy to an existing Tomcat or application server, or to use JSPs.

DevTools restarts the application automatically when classes on the classpath change, and turns off template caching during development. It uses two class loaders: libraries are loaded once, your code is reloaded, so a restart is faster than a cold start. Note: IntelliJ has to build (Ctrl+F9, or enable “Build project automatically”) for the classes to change.

Exercises

Exercise 1: Read the dependency tree

In a Spring Boot project with spring-boot-starter-web and spring-boot-starter-data-jpa: (a) find which starter brings in jackson-databind and Hibernate, (b) report the HikariCP version Boot picks, (c) add an old library that depends on a lower jackson-databind and explain which version Maven chooses.

Solution to exercise 1

(a) mvn dependency:tree -Dincludes=com.fasterxml.jackson.core:jackson-databind,org.hibernate.orm: Jackson arrives via spring-boot-starter-web → spring-boot-starter-json, Hibernate via spring-boot-starter-data-jpa.

(b) mvn help:evaluate -Dexpression=hikaricp.version -q -DforceStdout, or look for HikariCP in the tree.

(c) Because Jackson’s version is in Boot’s dependencyManagement, the managed version beats “nearest wins”: the whole tree uses Boot’s version. mvn dependency:tree -Dverbose shows a (version managed from …) note. If the library weren’t managed, the version nearer the root would win. To be sure, add the enforcer rule dependencyConvergence.

Exercise 2: Fix a download error

A colleague reports: “the build fails with Could not transfer artifact com.mysql:mysql-connector-j:jar:9.5.0, I deleted .m2 twice and it still fails; I’m on the office network”. Write the diagnosis steps and the fix.

Solution to exercise 2
  1. If the error survives wiping the cache, it’s not a broken cache but an unreachable repository. Try curl -I https://repo.maven.apache.org/maven2/ from that machine.
  2. Corporate proxy: add <proxies> to ~/.m2/settings.xml (host, port, nonProxyHosts).
  3. The company has Nexus/Artifactory: add a <mirror> with mirrorOf = central or *, plus a <server> with the same id for credentials.
  4. A TLS certificate re-signed by the proxy (PKIX path building failed): import the company CA into the truststore of the JDK running Maven; don’t disable TLS checks.
  5. Rerun ./mvnw -U package. Delete that artifact’s folder if *.lastUpdated files remain.

Remember

  • Can you explain how a phase differs from a goal, and why mvn package also runs the tests?
  • Do you know which scope to give a JDBC driver, a test library, and the servlet API in a war?
  • Can you read mvn dependency:tree to find who brought a library in and why that version won?
  • Do you know why not to write versions for Boot-managed libraries, and how to bump one safely with a property?
  • Can you fix a download error without wiping .m2?

Interview questions

Junior

What are groupId, artifactId and version for?

Together they are the unique coordinates of an artifact in a repository; Maven uses them to find and download the right file.

groupId is the organisation (reversed domain), artifactId the project name, version the release. The coordinates become a path in the repository, e.g. com/mysql/mysql-connector-j/9.5.0/. A -SNAPSHOT suffix means a work-in-progress build whose content may be replaced.

How do runtime and provided scope differ?

runtime: not needed to compile but present when the app runs. provided: needed to compile but not packaged, because the runtime environment already has it.

A JDBC driver is runtime because your code only uses the JDBC interfaces. The servlet API is provided when you deploy a war to an external Tomcat, which already ships it.

What is mvnw and why should you commit it?

The Maven wrapper: a script that downloads and runs the Maven version the project declares, so every machine and CI build with the same Maven without installing it.

Commit mvnw, mvnw.cmd and the .mvn/wrapper/ folder. Upgrading Maven is then a one-line change in maven-wrapper.properties.

Mid

How does a phase differ from a goal in Maven?

A phase is an ordered step in the lifecycle; a goal is one concrete task of a plugin. A phase does nothing by itself, it runs the goals bound to it.

Calling a phase runs every phase before it: mvn package runs compile, test, then jar:jar and spring-boot:repackage. Calling a goal (mvn spring-boot:run, mvn dependency:tree) runs only that goal.

Why do most dependencies in a Spring Boot project have no version?

Because spring-boot-starter-parent inherits the spring-boot-dependencies BOM, whose dependencyManagement pins versions for hundreds of libraries tested together.

dependencyManagement only sets versions, it adds no libraries. A project with another parent imports the BOM with <type>pom</type><scope>import</scope>. To change a version, override a property such as hibernate.version.

Two libraries pull in two versions of the same jar. Which one does Maven pick, and how do you handle it?

If the library is in dependencyManagement, the managed version wins; otherwise the version nearest the root wins, and on a tie the one declared first.

Inspect with mvn dependency:tree -Dverbose. Fix it by pinning the version in dependencyManagement, cutting the wrong branch with <exclusions>, and adding the enforcer’s dependencyConvergence so the build fails early instead of throwing NoSuchMethodError at runtime.

Senior

How does a Spring Boot fat jar run when Java cannot read nested jars?

The manifest points Main-Class at Boot’s JarLauncher; the launcher builds its own class loader over BOOT-INF/classes and the jars in BOOT-INF/lib, then calls main on Start-Class.

The JDK’s standard class loader can’t read nested jars. layers.idx splits the content into layers so Docker images reuse cache: rarely changing libraries below, frequently changing code on top. For faster startup you can extract the jar (-Djarmode=tools extract) or use CDS/AOT.

How do you protect the library supply chain of a Maven project?

Download only through a trusted repository (usually an internal proxy), pin versions through a BOM, scan for vulnerabilities automatically in CI, and keep the dependency list small.

  • An internal repository as the * mirror, no direct Internet downloads, HTTPS only, checksum policy fail.
  • Vulnerability scanning (OWASP Dependency-Check, Dependabot, Snyk) and an SBOM (CycloneDX).
  • Enforcer rules: no -SNAPSHOT in releases, banned libraries, converging versions.
  • dependency:analyze to remove declared but unused libraries.

Useful phrases for interviews

  • “Maven is a declarative build tool: the POM says what I need, the lifecycle says in which order things happen.”
  • “Calling a phase runs every earlier phase, so package also compiles and runs the tests.”
  • “The JDBC driver only needs runtime scope, because the code talks to the JDBC interfaces.”
  • “I let the Spring Boot BOM manage versions and only override a property when I need a security fix.”
  • “The old MySQL coordinates are relocated, so I switched to mysql-connector-j without a version.”
  • “Before wiping the local repository, I read which artifact failed and rerun with dash U.”
  • “All our downloads go through an internal Nexus mirror over HTTPS.”
  • “The fat jar embeds Tomcat and starts through Boot’s JarLauncher.”
  • “We use Flyway migrations in production and keep ddl-auto on validate.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.