What happens when I add a Maven dependency?

In general in all pom.xml we found dependency like this -

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Here groupId, artifactId and version are 3 keys by which a jar is uniquely identified. These 3 combination works like a coordinate system for uniquely identifying a point in a space using x, y and z coordinates.

Whenever you issue a mvn package command maven tries to add the the jar file indicating by the dependency to you build path. For doing this maven follows these steps -

  1. Maven search in your local repository (default is ~/.m2 for linux). If the dependency/jar is found here then it add the jar file to you build path. After that it uses required class file from the jar for compilation.

  2. If the dependency is not found in ~/.m2 then it looks for your local private repository (If you already have configured any using setting.xml file) and maven central remote repository respectively. If you don't have any local private repository then it directly goes to the maven central remote repository.

  3. Whenever the jar is found in the local/remote repository it is downloaded and saved in ~/.m2.

Going forward, when you again issue a mvn package command then it's never search for the dependency to any repository since it already in your ~/.m2.


If you have only the standard maven plugins from the default superpom, adding a dependency will:

  • download the specified version to your local repository
  • use it to compile
  • use it to run tests

There are several maven plugins which can be used to include dependencies in a package. These include:

  • maven-war-plugin
  • maven-ear-plugin
  • maven-assembly-plugin
  • appassembler-maven-plugin

In addition, the maven-shade-plugin can be used to combine your dependencies into the jar file of your own code.

None of these are used unless you add them to your pom.


Dependency will allow you to download 3rd party libraries using maven.

 <dependencies>
    <!--    Spring dependency -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.1.5.RELEASE</version>
    </dependency>
</dependencies>

for example it will import spring-core-4.1.5.RELEASE.jar under your maven dependencies. After you update the project using maven. Then you will able to use this jar in your code.

why can't Maven just look at my import statements and fully qualified names and figure out which dependencies I need?

Because what if there are same method that were overloaded by two different jars? Maven won't able to determine which one to import. Good example would be hibernate and JPA annotations. They're alike but yet use different imports.