Automatic versioning dependencies in child modules using parent pom, Java+maven

892 Views Asked by At

I have 3 repositories. In one there is parent-pom.xml, which is a parent for A1 and B1 repository. The B1 repository also has A1-repository in dependencies. If I change the version in parent-pom.xml, I have to manually change it also in A1-pom.xml and B1-pom.xml. Can it be automated somehow?

1

There are 1 best solutions below

2
On

As you said parent pom is the solution. If you declare in parent pom, you dont need to declare in child pom where the dependencies get inherited automatically. There are 2 concepts while declaring parent and child pom.xml

  1. Declare dependencies in parent pom.xml using <dependencies> tag.

Parent pom.xml

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

Child pom.xml

...
<parent>
    <groupId>com.xyz.local.dependency</groupId>
    <artifactId>xyz-dm</artifactId>
    <version>1.0</version>
</parent>   
...

Now you dont need to include this dependency in your child pom.xml unless you want to change the version. But the drawback of using is , child pom.xml will inherit all the dependencies irrespective of whether child needs the dependency or not.

  1. Declare dependencies in parent pom.xml using <dependencyManagement> tag.

Parent pom.xml

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

Child pom.xml

...
<parent>
    <groupId>com.xyz.local.dependency</groupId>
    <artifactId>xyz-dm</artifactId>
    <version>1.0</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
</dependencies>
...

With <dependencyManagement> tag, you are not actually including dependencies in child module. You need to declare the required dependencies explicitly if you need it. You dont need to mention the version of the dependency which will be taken from the parent pom.xml. This <dependencyManagement> tag will be very helpful when you have one common parent pom where you declare all dependencies, all the child pom.xml will inherit the version and declare the dependencies what they really need instead of inheriting every declared dependency.

For more clarity on <dependencies> and <dependencyManagement>, please refer this SO answers