Friday 7 September 2012

What The !@"#[: Are Maven Parent Projects?

All Maven projects have a parent project. If not declared explicitly, a project will automatically inherit from the super pom.xml. All projects inherit from the configuration of their parent project. It is possible to create relationships between parent and child projects.

Maven Project Inheritance

Assuming a project is divided in several modules, each module is a maven project in itself. The parent's pom.xml would be like:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mygroupid</groupId>
    <artifactId>myprojectparent</artifactId>
    <version>1.0.0</version>
</project>
This parent project inherits of the super pom.xml. A child module project would declare its parent relationship like this:
<project>
    <parent>
        <groupId>com.mygroupid</groupId>
        <artifactId>myprojectparent</artifactId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>mymoduleproject</artifactId>
</project>
The child module project does not inherit of the super pom.xml. By not specifying a group id or a version, it inherits these from its parent. The parent's pom.xml must be located in the directory above this module project. Else, the location must be specified relative to this module's pom.xml file. For example:
    <relativePath>.../parentDir/pom.xml</relativePath>

Maven Project Aggregation

There is another way to establish a relationship between a parent project and child projects: project aggregation. Instead of declaring a parent project in the child project, the parent project declares modules:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mygroupid</groupId>
    <artifactId>myprojectparent</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    <modules>
        <module>mymoduleproject</module>
    </modules>
</project>
The parent project's packaging must be set to pom and the pom.xml of child module projects must be located in directories bearing the module's name. Else, the module path must be specified relative to the
parent's pom.xml:
    <module>../myModuleDir/mymoduleproject</module>
If one compiles the parent project (or performs any other action on it), all its modules are compiled too.

REM: In this configuration, there is no inheritance between child projects and the parent project (only aggregation). Hence, child projects do not inherit of the parent's configuration. All projects of this aggregation inherit of the super pom.xml. They each have a life of their own.

No comments:

Post a Comment