Favor composition over inheritance with maven dependencies

Favoring composition over inheritance is one of the main principles I’ve been applying throughout my oo programming career. But this principle can not only be applied to programs but also to the dependency management in maven. This post examines ehe import scope for dependencies to use composition rather than inheritance in maven dependency management.

When trying to properly configure dependencies in maven up until now I have been using parent poms that declare dependencies and child poms that then use theses dependencies. Recently I stumbled across the import scope in the dependency management section that let’s you include dependencies through composition rather then inheritance.

As explained in the maven guide above: “the imported POM is be replaced with the dependencies in that POM’s <dependencyManagement> section.”. That is, if you can add dependencies by importing a pom which you then can use later.

I’ve made a little example here that contains a pom that declares some spring boot dependencies:

Where the name of the spring version to use has been put into properties of the same pom.

In another maven project, which is not a child of the project above, I imported the project above:

Now I can use any of the dependencies in the project:

The output of the command

shows that the dependency to the imported project have been replaced by the onces declared in that imported project:

Possible application

Now what is so special about this type of reusing dependencies declared in other maven project ?

The most obvious benefit is, that you can reuse the dependencies without creating a parent child relationship:

Using the import scope enable dependency management through composition rather than through inheritance.

This enable the reuse of dependencies over projects that are otherwise not related.

In my current project for example I have an application which is made up of three parts that are independently build. All three use spring. So I created a maven project which declares all the spring dependencies and versions to use. I can use this pom in all the other parts without inheriting other parts.

Cool :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">