How to add Maven Dependencies in Pom.xml

 

In Maven, adding external dependencies means telling Maven which libraries your project needs, so it can automatically download them from a remote repository (like Maven Central) and include them in your build.


 What is a Dependency in Maven?

dependency is an external Java library (JAR file) your project needs to compile or run. You declare dependencies in the pom.xml file.


How to Add External Dependencies in Maven?

1. Locate Dependency Info

You need to know:

  • groupId

  • artifactId

  • version

You can find these on https://mvnrepository.com



2. Add Dependency to pom.xml


<dependencies>
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
  </dependency>
</dependencies>




Maven will:

  • Download it from Maven Central

  • Store it in your local .m2 repository

  • Add it to your project classpath





 Example: Adding Multiple Dependencies


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

  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
  </dependency>
</dependencies>

No comments:

Post a Comment