26

I've downloaded a source code from internet and I'm trying to build it with maven. Here is the pom.xml file that came with the source code:

<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/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myArtifact</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>myArtifact</name>
<url>http://maven.apache.org</url>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <mainClass>myArtifact.Main</mainClass>
                    </manifest>
                </archive>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>8.4-701.jdbc4</version>
        <scope>compile</scope>
    </dependency>
</dependencies>
</project>

The mvn install command is generating the jar file but I'm unable to execute this file because of the missing dependencies (class not found exception related to postgresql dependency in this example).

I've noticed that maven has downloaded the dependencies correctly (the jar libraries are all at the local maven repository directory) but mvn install is not copying these libraries into the generated jar file. How can I do this?

Thanks.

Fernando Magalhães
  • 539
  • 2
  • 9
  • 17

1 Answers1

20

Remove the descriptorRefs and archive tag from your maven-compiler-plugin section.

In order to generate a JAR with all the dependencies self contained. You need to put this into the build plugins section of your pom.xml:

<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>
                            com.test.your.main.class.goes.Here
                        </mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
</build>

Create the JAR file by running the following at the command prompt:

mvn clean compile assembly:single
Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Neeraj Verma
  • 330
  • 2
  • 6