Adding Maven Dependencies
Prerequisites
Before adding Maven dependencies, ensure you have:
- Java Development Kit (JDK)
- Maven installed on Ubuntu 22.04
Step-by-Step Dependency Addition
1. Locate pom.xml File
Every Maven project has a pom.xml
file in its root directory. This is where dependencies are declared.
graph TD
A[Project Root] --> B[pom.xml]
B --> C[Dependencies Section]
2. Dependency Syntax
Basic dependency structure in pom.xml
:
<dependencies>
<dependency>
<groupId>group-name</groupId>
<artifactId>artifact-name</artifactId>
<version>version-number</version>
<scope>optional-scope</scope>
</dependency>
</dependencies>
3. Common Dependency Examples
Library |
GroupId |
ArtifactId |
Use Case |
JUnit |
junit |
junit |
Unit Testing |
Spring Core |
org.springframework |
spring-core |
Web Framework |
Apache Commons |
org.apache.commons |
commons-lang3 |
Utility Functions |
4. Adding a Dependency: Practical Example
Let's add the Apache Commons Lang library:
## Open pom.xml in text editor
sudo nano pom.xml
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
5. Dependency Management Commands
## Download dependencies
mvn clean install
## Update dependencies
mvn dependency:resolve
## List all dependencies
mvn dependency:tree
Advanced Dependency Management
Exclusions
Remove unwanted transitive dependencies:
<dependency>
<groupId>example</groupId>
<artifactId>library</artifactId>
<exclusions>
<exclusion>
<groupId>unwanted-library</groupId>
<artifactId>artifact</artifactId>
</exclusion>
</exclusions>
</dependency>
Version Management
graph TD
A[Version Management] --> B[Use Property Tags]
A --> C[Use Bill of Materials]
A --> D[Centralize Version Control]
Best Practices
- Use specific, stable versions
- Minimize dependency count
- Regularly update dependencies
- Check for compatibility
With LabEx's comprehensive guides, mastering Maven dependencies becomes straightforward and efficient.