How do I include external JARs in my own Project J

2020-07-03 08:12发布

I have a Java application and created a JAR file and deployed it.

The App uses external JARs such as the Log4J JAR. When creating my JAR file, how do I include all external dependent JARs into my archive?

In order to get my App working, I'm having to copy the Log4J JAR into the same directory as my own JAR which kinda defeats the purpose of the jar. Wouldn't it be more elegant to have 1 single JAR file to deploy?

6条回答
三岁会撩人
2楼-- · 2020-07-03 08:35

You could use something like One-JAR to package your Java application together with its dependency into a single executable Jar file (One-JAR uses a custom classloader to make JARs nesting possible).

查看更多
Luminary・发光体
3楼-- · 2020-07-03 08:35

You can use Maven + assembly plugin (http://maven.apache.org/plugins/maven-assembly-plugin/)

BTW, probably that's not the easiest way, if you did not work with maven.

查看更多
家丑人穷心不美
4楼-- · 2020-07-03 08:38

If you use Eclipse, You can extract all included files into one runnable jar like this:

  1. Right click on your project name from Package Explorer and select Export.
  2. In Export screen, select Java -> Runnable JAR file and Next.
  3. Fill in the Runnable JAR File Spec screen and Finish.

You can choose whether to package dependency jars as individual jar files or extract them into the generated JAR.

查看更多
萌系小妹纸
5楼-- · 2020-07-03 08:38

A JAR is not itself capable of nesting other JARs, as you discovered.

Traditionally, one would distribute a ZIP archive or other installer that would unwind the application JAR (yours) as well as any support JARs in the appropriate location for classpath access. Frequently, then, the application was invoked through a script that invoked the primary JAR and created a classpath that listed the support JARs.

As other posters have noted, you have some options to create a super-JAR if that's what you want.

查看更多
smile是对你的礼貌
6楼-- · 2020-07-03 08:41

Keeping JAR separate is better as it is easy to upgrade only the specific JARs to its new versions without touching any other configuration. As of your issue of having to copy each file to same location as of your JAR, you can always use Java CLASSPATH and include any JAR to your application's class path.

查看更多
Explosion°爆炸
7楼-- · 2020-07-03 08:45

You have to expand the library jars into the same place where your compiled classes go, then make a jar from that. Depending on how your build process is set up, there may be multiple ways to achieve this. It's not rocket science - a jar is just a zip archive with a META-INF directory at the root level.

查看更多
登录 后发表回答