Thursday, February 3, 2011

Maven dependency example explained

One of the features of Maven over ant tool is dependencies management for software projects.
When you are using maven in your project, you need to define the dependencies in pom.xml, once the dependencies are defined, these will be downloaded into your local machine from repositories. To configure the dependencies, you have to use the dependency plugin which manipulates the artifacts when you are installing with maven
So here is sample code snippet for configuring spring-core to your project
When you compiled, your project downloads spring-core jar for the first time from the spring repository server. You also should have to configure repository server in pom.xml with the following piece of code.
So you can configure multiple repositories, the order of repositories that looks for the artifact should have to mention in the order in pom.xml

What is a transitive dependency in maven?

For example, Take the scenario, what happened if the spring-core artifact has log4j as one of dependency. Should log4j dependency also download into your local project? Yes, all the direct dependencies should resolve automatically. Transitive dependency meaning is that all the dependencies resolve for your project transitively configured in pom.xml.
Understanding maven dependency  with example

In this example, your project is configured only spring-core, but your project has indirect dependencies log4j and JMX which are dependent on spring-core. So maven resolves all these dependencies and your project has all direct and indirect these dependencies.
Your project 1.0.0 has spring-core-2.5.6 direct dependency, log4j-1.2.12 and jmx-1.0.2 indirect dependencies

As per your project needs, you want to use log4j-1.2.14 only, but as per above spring-core dependency, you got log4j-1.2.12 as a dependency. So you have to avoid log4j-1.2.12 dependency.

For this, we have to use an exclusion tag in pom.xml in dependency tag. Following is the code snippet
<groupid>log4j </groupid>
</dependency> This topic has been a very basic start to explore on maven dependency example. Hopefully, you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.


Note: Only a member of this blog may post a comment.