英文:
Lightweight way to use a Maven dependency?
问题
当您想要使用某个Java库中的某个实用程序时,通常会怎么做?我的意思是,如果将它作为Maven依赖项添加,整个库是否会被包含在汇编的JAR中?
我没有任何存储问题,也不介意JAR变得臃肿,但我只是好奇是否有某种策略可以减小这种情况下的JAR大小。
谢谢
英文:
What do you normally do when you want to make use of some utility which is part of some Java library? I mean, if you add it as a Maven dependency is the whole library get included in the assembled JAR?
I don't have storage problems of any sort and I don't mind the JAR to get bloated but I'm just curious if there's some strategy to reduce the JAR size in this case.
Thanks
答案1
得分: 1
这甚至更糟:你不仅向你的项目中添加了“整个库”,还有它的依赖项,无论你是否需要它们。
Joachim Sauer 在他说的话中是正确的,即除非你想要运行它,否则不要将依赖项捆绑到你的构件中。但在我看来,这只是把问题转移到了另一个点上。最终,你想要运行这些东西。在某个时候,会构建一个可运行的 JAR、WAR 或 EAR 文件,它将包含整个依赖树(减去每个构件只获取一个版本的事实)。
Maven shade 插件可以帮助你最小化你的 JAR(参见 https://stackoverflow.com/q/8817257/927493),只添加“必要”的类。但这在一般情况下当然是棘手的:
- 非 Java 元素引用的类无法找到。
- 反射使用的类无法找到。
- 如果你正在使用一些依赖注入,你只在代码中使用接口。因此,实现可能会被剔除。
所以,你的 minimizedJar 通常可能会太小。
正如你所见,我不知道任何一般性的解决方案。
有哪些明智的方法呢?
- 不要构建具有五个目标的 JAR 文件,而是构建小型的 JAR 文件。为了避免大量不同的构建过程,使用多模块项目。
- 除非你确实需要,否则不要将库添加为依赖项。最好是复制一个方法来转换字符串,而不是为此目的添加一个完整的字符串库。
英文:
It is even worse: You do not only add the "whole library" to your project, but also its dependencies, whether you need them or not.
Joachim Sauer is right in saying that you do not bundle dependencies into your artifact unless you want it to be runnable. But IMHO this just moves the problem to a different point. Eventually, you want to run the stuff. At some point, a runnable JAR, a WAR or an EAR is built and it will incorporate the whole dependency tree (minus the fact that you get only one version per artifact).
The Maven shade plugin can help you to minimise your jar (see https://stackoverflow.com/q/8817257/927493) by only adding the "necessary" classes. But this is of course tricky in general:
- Classes referenced by non-Java elements are not found.
- Classes used by reflection are not found.
- If you have some dependency injection going on, you only use the interfaces in your code. So the implementations might get kicked out.
So your minimizedJar might in general just be too small.
As you see I don't know any general solution for this.
What are sensible approaches?
- Don't build JARs that have five purposes, but build JARs that are small. To avoid a huge number of different build processes, use multi-module projects.
- Don't add libraries as dependencies unless you really need them. Better duplicate a method to convert Strings instead of adding a whole String library just for this purpose.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论