Wednesday, March 21, 2012

Maven - modular projects

Sometimes projects are functionally so tightly coupled, that modifying one always involves modifying the other.

For example, if you use GWT (we will learn this later), you always have to write client and server side code. Client side code runs in the browser, while Server side code handles the AJAX requests coming from the client.

Each has its own Maven project, but making changes to one invariably requires changes to other. Consequently, when one is built, the other needs to be built as well.

For cases like this, Maven provides a concept called modular projects.

You can create a parent project and declare other projects as modules of the parent project. Now whenever you build the parent project, all the modules are automatically built.

The pom.xml of the parent project declares who its modules are.
And the pom.xml of the module projects declare who their parent is.

Let us see this with an example.

In Eclipse,
1. Go to File-->New-->Maven-->Maven Project

2. Select 'Create a simple project'
Click Next

3. Specify
Group Id --> org.confucius
Artifact Id --> HelloWorldParent
Packaging --> pom (this means that this project does not really build anything!)

Click Finish.

Now let us create the modules.
1. Go to File-->New-->Maven-->Maven Module

2. Select 'Create a simple project'
Specify Module Name --> HelloWorldClient
Specify parent Project --> HelloWorldParent

Click Next.

3. Specify:
Group Id --> org.confucius.HelloWorldParent (Note that we add the parent's artifact id to the group Id)

Click Finish.

Repeat above steps to create HelloWorldServer module.

If you now open the pom.xml of the HelloWorldParent, you will see that m2eclipse has created a <modules> section.

If you open the pom.xml of the modules, you will see that it contains a <parent> section.

Right click on the HelloWorldParent project in Eclipse navigator view and select Run As-->Maven install.

You will see in the console that this builds all of the modules of the project.

If you go to your Windows file browser, you will see that the HelloWorldClient and HelloWorldServer project folders are created inside the HelloWorldParent project folder.

Module project folders are always put inside parent project folders.

Note:
Modular projects create certain challenges with respect to version control systems. You cannot branch a module without branching the parent and all the other modules!

Secondly, if one of the modules jar is made a dependency in some other project, this might cause issues when you want to upgrade the module, but not the parent.

For these reasons, it is better to use modular projects only in cases where you know for sure that the projects are tightly coupled. And there is no other project that depends on one of the modules.

No comments: