How to Set Up a Maven Project in Netbeans

I've been using Netbeans for years and I love how easy it is to set up a project, add dependencies, build a jar file, and run it in a shell/command prompt.

I recently waded into the Maven world and was a little put off by how difficult it is to set up a new Maven project in Netbeans. It is not as intuitive as I had hoped. Adding dependencies and packaging a build to run from a command prompt requires editing an XML file. I know its not hard to do but what year is this, the 2001?

This tutorial is intended to help me in the future, should I ever need to create another Maven project in Netbeans.

Packaging a Build

Goals:
  • All the dependencies in a separate lib folder
  • The main project jar with a manifest that includes the lib folder on it's classpath

Add the following spinnet to the pom.xml to identify the main class. Replace "project.Main.class" with the name of your class, prefixed with the package name.

<properties>
        <mainClass>project.Main.class</mainClass>
</properties>

Next, you will need to add a plugin to run the main class with its dependencies. You do not have to edit any of the variables in the following snippet.

<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <phase>install</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>${mainClass}</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

Adding Dependencies

To add a jar file to you project, you will need to add a "dependency" tag to your pom.xml. Example:

<dependencies>
   <dependency>
     <groupId>javaxt</groupId>
     <artifactId>javaxt-core</artifactId>
     <version>1.8.1</version>
   </dependency>
 </dependencies>

Netbeans assumes that the dependencies you specified above are found in Maven Central. If not, you will need to add a repository to your pom.xml file so Netbeans knows where to find the jar files. Example:

<repositories>
   <repository>
     <id>javaxt.com</id>
     <url>http://www.javaxt.com/maven</url>
   </repository>
</repositories>

Finally, you may need to tell Netbeans to download the dependencies. Click on the Project node -> Resolve Missing Dependencies -> Resolve...

References

  • https://stackoverflow.com/questions/17654213/how-do-i-create-a-netbeans-style-jar-with-all-dependencies-in-a-lib-folder/
  • https://gist.github.com/daluu/52af7eef52563ddf78fe