在多个项目中共享 JAR 的最佳方式是什么?

2022-01-25 00:00:00 include java eclipse jar

When you have multiple projects that all use the same set of JAR libraries, it's tedious to include the same JARs over and over again with each project. If I'm working on 20 different projects, I'd rather not have 20 of the same exact set of JAR files lying around. What's the best way to make all those projects (and new projects as well) reference the same set of JARs?

I have some ideas, but each of them has some disadvantages:

  • Place all the JARs in a folder and have each project look in that folder.
  • Using Eclipse, create a "User Library" and have each project reference that user library.
  • Create a "Library" project that references each JAR, and have each project reference that library project.

解决方案

Use Maven or Ivy to handle these shared jars. If you're wary of changing your projects too much, you can simply use Ivy to manage the extra classpath for you.


Both have good Eclipse plugins:

m2eclipse

Maven classpath container http://img229.imageshack.us/img229/4848/mavendependencies.png

IvyDE

IvyDE classpath container http://img76.imageshack.us/img76/3180/cpnode.jpg

which I've used with good results.

You'll note that both of them reference jars outside the workspace, so the duplication is removed.


Update ( prompted by comments ):

My reason for recommending this approach is that I strongly believe that it's simpler and clearer to declare dependencies rather then manually include them. There is a small one-time cost associated with this - smaller for Ivy than for Maven - but in the long run it does pay off.

Another, smaller, benefit is the handling of transitive and conflicting dependencies. It's easy to forget why you need that commons-logging-1.1.jar in the classpath and whether you need to upgrade to 1.1.1. And also it's no fun to pull in all the depencies required for e.g. a Hibernate + Annotation + Spring combo. Focus on programming, not building.

相关文章