Combining inheritance and aggregation

By using the project inheritance feature of Maven, we can share common build attributes such as properties and dependencies across all children. We can also aggregate modules and build them together.

When project inheritance is used, the parent is not aware of the child. In the case of project aggregation, each module is not aware of the aggregation.

We will now see how to combine and get the benefits of both.

How to do it...

  1. Open a multi-module project; in our case, simple-multi-module. This has a subfolder child, which is the module that is aggregated by the parent project.
  2. Update the parent pom as follows:
        <groupId>com.packt.cookbook</groupId>
        <artifactId>simple-multi-module</artifactId>
        <packaging>pom</packaging>
        <version>1.0-SNAPSHOT</version>
  3. Add the module section and specify the child:
       <modules>
          <module>child</module>
  4. Update the child pom to specify the parent element:
        <parent>
          <groupId>com.packt.cookbook</groupId>
          <artifactId>simple-multi-module</artifactId>
          <version>1.0-SNAPSHOT</version>
         </parent>
  5. Run the following Maven command in the parent folder:
    mvn clean package
    
  6. Observe the output:
    [INFO] Reactor Summary:
    [INFO]
    [INFO] simple-multi-module ................................ SUCCESS [  0.162 s]
    [INFO] Child Project ...................................... SUCCESS [  2.411 s]
    

How it works...

We have specified the parent element in the child pom to indicate who the parent is. We have also specified the child project as a module in the parent pom. Thus, both the relationships—inheritance and aggregation—are defined.

When we build the parent project, it automatically builds the child by virtue of the modules element. At the same time, the child project can be built independently as well.

There's more...

The child project need not necessarily be a subfolder of the parent project. If it is elsewhere, as we have seen in the earlier recipes, it can be one of the following:

  • relativePath: relativePath of the parent element should point to the appropriate location of the parent
  • module: The module element should contain the appropriate path to the child project
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233