Tuesday, 9 July 2019

Maven: dependencyManagement element


Suppose there are multiple projects are being developed in your organization. Assume in all the projects 80% of the libraries are common.

Let’s go with first approach: where you specify the dependencies of all the projects separately in their respective pom files. Assume 450 projects out of 500 are using junit version 4.4. Suppose your organization wants to use junit version 4.12. We will be end up in updating all the 450 files manually.

Let’s go with second approach : You specify all the common dependencies in a pom file using <dependencyManagement> elements. Make sure all the projects inherit the dependencies from this parent pom. In this approach, you just need to change the version in one place.

Parent Pom
<project>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.parentProject</groupId>
   <artifactId>org.parentProject</artifactId>
   <version>1</version>
   <name>Parent Dependencies</name>
   
 <dependencyManagement>
  <dependencies>
  
   <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
   </dependency>

  </dependencies>
 </dependencyManagement>
   
   <properties>
  <junit.version>4.12</junit.version>
   </properties>
   
</project>


Child Pom
<project>
 <modelVersion>4.0.0</modelVersion>
 
 <parent>
  <groupId>org.parentProject</groupId>
  <artifactId>org.parentProject</artifactId>
  <version>1</version>
 </parent>

 <artifactId>child project1</artifactId>
 <groupId>child project1</groupId>
 <version>1</version>
 
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
  </dependency>
 </dependencies>
</project>

You may ask me, why should I used dependencyManagement element to specify all the common dependencies. Why can’t I use <dependencies> elements to specify the dependencies.

Artifacts specified in the <dependencies> section will ALWAYS be included as a dependency of the child module(s). Artifacts specified in the <dependencyManagement> section, will only be included in the child module if they were also specified in the <dependencies> section of the child module itself.




Previous                                                    Next                                                    Home

No comments:

Post a Comment