Home > Enterprise >  Inheriting the version of an optional dependency
Inheriting the version of an optional dependency

Time:03-25

My company has 3 Maven projects organized as follows:

Project A depends on Project B.

Project B depends on Project C. (Project B has set Project C as an Optional dependency in their POM)

I am the owner of Project A. I would like to add Project C as a direct dependency in my POM. However, I do not want to be responsible for keeping the version of Project C up to date. Is there a way I can inherit the version of Project C specified in Project B's POM at all times?

CodePudding user response:

If you don't control project B, it's not possible, except possibly with some plugin hackery.

If you do control project B then you can declare a dependency management section in that project which you can additionally import into project A.

Project B POM

<dependencyManagement>
    <groupId>com.foo</groupId>
    <artifactId>project-c</artifactId>
    <version>1.2.3</version>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>com.foo</groupId>
        <artifactId>project-c</artifactId>
        <!-- no need for version here, comes from dependencyManagement -->
        <optional>true</optional>
    </dependency>
</dependencies>

Project A POM

<properties>
    <!-- using a property isn't necessary, but ensures the
         POM import and dependency stay in sync -->
    <project.b.version>2.3.4</project.b.version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.foo</groupId>
            <artifactId>project-b</artifactId>
            <version>${project.b.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>com.foo</groupId>
        <artifactId>project-b</artifactId>
        <version>${project.b.version}</version>
    </dependency>
    <dependency>
        <groupId>com.foo</groupId>
        <artifactId>project-c</artifactId>
        <!-- version is not necessary, imported from project-b's dependency management -->
    </dependency>
</dependencies>

This will mean Project A will default to Project B for all dependencies in B's dependency management section. I don't think there's a way to restrict it to just a specific one. I doubt you'll care but just something to be aware of.

Any versions that Project A defines, either in its own dependency management or directly in <dependencies>, will override any version brought in from Project B's dependency management.

  • Related