1

I was wondering if it is possible to "package in" dependencies while using mvn compile.

When I do compile my program with mvn install I do get clean and great result as expected, but after I package it into .jar suddenly I get missing classes exceptions.

I have read that it may be caused by differences in build and package class paths but I am unable to fix it.

Exception screen

Thanks a lot.

PapeK24
  • 988
  • 1
  • 10
  • 26
  • 2
    Yes, you can use a tool called [OneJar](http://one-jar.sourceforge.net) or you can generate what's known as a "fat jar", which basically unjars everything and combines into a single jar. Maven prefers fat jars, I personally don't as I tend to place property/configuration files in the my jars which share the same name, so it screws things up. – MadProgrammer Oct 31 '17 at 00:47
  • 2
    Another approach is to include the `class-path` entry in the manifest file to point to the location of the external libraries, [for example](https://stackoverflow.com/questions/24899985/this-project-cannot-be-added-because-it-does-not-produce-a-jar-file-using-an-ant/24900260#24900260) – MadProgrammer Oct 31 '17 at 00:47
  • Works like a charm. Thank you! – PapeK24 Oct 31 '17 at 00:53
  • The basic problem is that the default classloaders in the Java runtime library does not support classes in jars inside jars. Hence a lot of different approaches has been tried. Either repack all classes in a single jar ("shaded jar") or have Maven create a launcher script with needed files which sets the classpath and run the program. I prefer the latter for non-trivial things - see http://www.mojohaus.org/appassembler/appassembler-maven-plugin/assemble-mojo.html – Thorbjørn Ravn Andersen Oct 31 '17 at 08:46
  • Also consider just using maven to run your program. The exec-maven-plugin allows you to run classes with `mvn -q exec:java`. See https://github.com/ravn/dagger2-hello-world for a tiny example. – Thorbjørn Ravn Andersen Oct 31 '17 at 08:48

1 Answers1

1

It sounds like an executable shaded jar you're looking for.

How to make executable jar?

https://github.com/renfeng/elo-rating/blob/master/cli/pom.xml#L32-L51

How to make shaded jar?

https://github.com/renfeng/elo-rating/blob/master/cli/pom.xml#L52-L67

Alternatively, you can

  1. Package dependencies with assembly plugin, and

https://github.com/renfeng/elo-rating/blob/master/cli/src/main/assembly/dist.xml#L30-L33

  1. Launch with class path specified.

https://github.com/renfeng/elo-rating/blob/master/cli/elo#L4

Or, you can settle somewhere in the middle, like my github sample project does.

Frank R.
  • 1,732
  • 18
  • 21