views:

535

answers:

4

Hi, is there a way to force maven(2.0.9) to include all the dependencies into jar file?
I have a project the builds into a single jar file. I want that the classes from dependencies will be copied as well.
Update: I know that I cant just include a jar file into a jar file. I'm searching for a way to unpack the jars that are specified as dependencies, and package class files into my jar.

+4  A: 

You can do this using the maven-assembly plugin with the "jar-with-dependencies" descriptor. Here's the relevant chunk from one of our pom.xml's that does this:

  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>attached</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin>
John Stauffer
The `attached` goal is deprecated. The `single` or `directory-single` goal should be preferred instead.
Pascal Thivent
A: 

There's the shade maven plugin. It can be used to package and rename dependencies (to omit dependency problems on the classpath).

Thomas Jung
+5  A: 

With Maven 2, the right way to do this is to use the Maven2 Assembly Plugin which has a pre-defined descriptor file for this purpose and that you could just use on the command line:

mvn assembly:assembly -DdescriptorId=jar-with-dependencies

If you want to make this jar executable, just add the main class to be run to the plugin configuration:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <mainClass>my.package.to.my.MainClass</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

If you want to create that assembly as part of the normal build process, you should bind the single or directory-single goal (the assembly goal should ONLY be run from the command line) to a lifecycle phase (package makes sense), something like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <executions>
    <execution>
      <id>create-my-bundle</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
      <configuration>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        ...
      </configuration>
    </execution>
  <executions>
</plugin>

Adapt the configuration element to suit your needs (for example with the manifest stuff as spoken).

Pascal Thivent
A: 

Putting Maven aside, you can put JAR libraries inside the Main Jar but you will need to use your own classloader.

Check this project: One-JAR link text

medopal