Wednesday, May 12, 2010

How to Copy Dependencies and Automatically Add the Classpath into Manifest File

One thing that I like from NetBeans project for desktop applications is that it can include all the dependencies in dist/lib and include those dependencies in the MANIFEST.MF's classpath, so that we can just do java -jar or double click on the JAR. As a Maven user, I can achieve similar objective by adding few lines in my pom.xml.

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>myproject.Main</mainClass>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>lib/</classpathPrefix>
                </manifest>
                <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
            </archive>
        </configuration>
    </plugin>
    <plugin>
        <groupid>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/lib</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

The maven-dependency plugin is used to copy the dependencies in the target/lib. The maven-jar-plugin is used to create a MANIFEST.MF file and automatically add the classpath as well as mainClass. You need to make sure that an empty MANIFEST.MF is present in the src/main/resources/META-INF.

3 comments:

  1. Typo in org.apache.maven.plugins

    Should be:
    org.apache.maven.plugins

    Thanks for the info.

    Don

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. typo: groupId with capital I

    ReplyDelete