Config Java multi-module project in Maven

0
2358
Config Java multi-module project in Maven
Config Java multi-module project in Maven

When you have many sub-projects, or so-called modules, related to a project and you want to organize them efficiently in a single project, you can use Maven multi-module feature.

To enable this feature, you will need to create an empty parent project with no code specified since code will be provided through each module (sub-project).The pom.xml of the parent project should define the packaging type.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.petehouston.maven</groupId>
    <artifactId>multi-module-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>pom</packaging>

</project>

In order to add a module, simply create a new Maven project at same level of the parent pom.xml.
The module’s pom.xml should refer to the parent project like following:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>multi-module-example</artifactId>
        <groupId>com.petehouston.maven</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>module-01</artifactId>

</project>

Final step is to let parent project know about its children by specifying the module in the pom.xml:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.petehouston.maven</groupId>
    <artifactId>multi-module-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>module01</module>
        <module>module02</module>
    </modules>

    <packaging>pom</packaging>

</project>

Congratulation! You have a working multi-module project now.