How do I create/use a class library with Netbeans on top of Maven?

AlanObject picture AlanObject · Feb 25, 2012 · Viewed 8.4k times · Source

This seems like a stupid question, but I am sort of dependent on Netbeans 7.1 wizards. There doesn't seem to be an option to do this.

My web-app is built with Maven and I want to break out some of its packages into an independently built and maintained class library (specifically, the JPA part but that shouldn't matter.) Then I want to delete those packages out of the original web application and then create a dependency to the artifact that I create.

So how do I get started? The Netbeans New-Project wizard doesn't seem have an option for "Java Class Library" like it does for ANT-built projects. The closest choice I can see is "Java Application." Is that what I use and just ignore the main class or is there some other path I don't see?

I am usually pretty good at picking this stuff up but my web searches aren't yielding much. Much thanks for any help.

Answer

Jörn Horstmann picture Jörn Horstmann · Feb 25, 2012

You can use the wizard for "Maven" -> "Java Application (A simple Java SE application using Maven)", as far as maven is concerned there is no difference between a libary and an application. I think netbeans will create a sample App.java that you can simply delete.

For your usecase it would make sense to also create a parent project for the library and the webapplication. Building the parent would then also build both the library and web application. It also allows you to use "build with dependencies" on the web application and have the library rebuilt first.

To create a parent project you can use the "POM Project" entry. The directory structure ideally looks like this:

- pom.xml (for parent project)
- library (folder)
    - pom.xml (for library module)
- webapp  (folder)
    - pom.xml (for webapp module)

The parent project should then contain module elements containing the relative path of your other projects:

<modules>
    <module>library</module>
    <module>webapp</module>
</modules>

The library and web application reference the parent like this, the groupId and version are defaulted to be the same as the parent:

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>myGroupId</groupId>
    <artifactId>parentArtifactId</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
</parent>
<artifactId>libraryArtifactId</artifactId>