开发者

What is the best practice for including third party jar files in a Java program?

开发者 https://www.devze.com 2022-12-22 16:07 出处:网络
I have a program that needs several third-party libraries, and at the moment it is packaged like so: zerobot.jar (my file)

I have a program that needs several third-party libraries, and at the moment it is packaged like so:

zerobot.jar (my file)
libs/pircbot开发者_如何学Go.jar
libs/mysql-connector-java-5.1.10-bin.jar
libs/c3p0-0.9.1.2.jar

As far as I know the "best" way to handle third-party libs is to put them on the classpath in the manifest of my jar file, which will work cross-platform, won't slow down launch (which bundling them might) and doesn't run into legal issues (which repackaging might).

The problem is for users who supply the third party libraries themselves (example use case, upgrading them to fix a bug). Two of the libraries have the version number in the file, which adds hassle.

My current solution is that my program has a bootstrapping process which makes a new classloader and instantiates the program proper using it. This custom classloader adds all .jar files in lib/ to its classpath.

My current way works fine, but I now have two custom classloaders in my application and a recent change to the code has caused issues that are difficult to debug, so if there is a better way I'd like to remove this complexity. It also seems like over-engineering for what I'm sure is a very common situation.

So my question is, how should I be doing this?


We provide script files with the jar. E.g. some.bat, some.sh etc.

And as of Java6, you can use wildcard to specify classpaths.

Here is a good article that explains this approach : https://blogs.oracle.com/mr/entry/class_path_wildcards_in_mustang


If your audience is technical (and it sounds like they are if they're willing to drop in new jar files) then perhaps you could supply .sh and .bat files that they can edit to modify the classpath? That will be more transparent to them than a custom classloader.


You can try the Fat-Jar solution, it works perfectly with the 'Fat Jar Eclipse Plug-In'. I have used for a few projects with no problems at all. The principle of it seems to be the same of your current solution.


I think I'm going to go the manifest route. Declare the classpath in the manifest for the entry jar, and have entries for:

libs/pircbot.jar
libs/mysql-connector-java-5-bin.jar
libs/c3p0.jar

Then if users want to upgrade to the latest library versions, they will have to rename them to match what is declared in the manifest. I don't think that's too big a hassle, and it makes things a lot simpler internally.

I also just generally don't like the idea of loading everything in ./lib/ automatically, that seems potentially dangerous.

0

精彩评论

暂无评论...
验证码 换一张
取 消