There are times when you might want a project to use values from another .pom
file. You may be building a large software product, so you do not want to repeat the dependency and other elements multiple times.
Maven provides a feature called project inheritance for this. Maven allows a number of elements specified in the parent pom file to be merged to the inheriting project. In fact, the super pom file is an example of project inheritance.
Maven is set up on your system and is verified to work. To do this, refer to Chapter 1, Getting Started.
child
, which is the project that inherits from the parent.<groupId>com.packt.cookbook</groupId> <artifactId>project-with-inheritance</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version>
child
as follows:<parent> <groupId>com.packt.cookbook</groupId> <artifactId>project-with-inheritance</artifactId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>child</artifactId> <packaging>jar</packaging> <name>Child Project</name>
child
subfolder:mvn clean package
We specified a parent
element in the pom file of child
. Here, we added the coordinates of the parent, namely groupId
, artifactId
, and version
. We did not specify the groupId
and version
coordinates of the child
project. We also did not specify any properties
and dependencies
.
In the parent pom file, we specified properties
and dependencies
.
Due to the relationship defined, when Maven runs on the child
project, it inherits groupId
, version
, properties
, and dependencies
defined in the parent.
Interestingly, the parent pom file (project-with-inheritance
) is oblivious to the fact that there is a child
project.
However, this only works if the parent project is of the pom
type.
How did Maven know where the parent pom is located? We did not specify a location in the pom file. This is because, by default, Maven looks for the parent pom in the parent folder of child
. Otherwise, it attempts to download the parent pom from the repository.
What if the parent pom is not in any repository? Also, what if it is in a different folder from the parent folder of the child? Let's see what happens:
parent
folder but in a subfolder (in our case, parent
):<parent> <groupId>com.packt.cookbook</groupId> <artifactId>parent</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent>
child
project:mvn clean package
Maven now determines the location of the parent pom by virtue of the relativePath
element, which indicates the folder where the parent pom is located. Using this, it builds the child project successfully.
3.144.17.128