简体   繁体   中英

maven-shade-plugin and singletons

I think I already know the answer, but would appreciate if someone can confirm it for me.

A) We are including a library in a build using maven-shade-plugin;
B) This library implements singleton(s);
C) Our resulting jar (uber-jar) is, in turn, used in a build of a megaproject;
D) Other jars in a megaproject also using the same library (A);

Would the library (A) be not acting as a singleton across the entire megaproject? Would we end up with a separate set of static variables for each shaded copy of an artifact? Would using maven-assembly-plugin instead of maven-shade plugin help?

You described a scenario in which the same class could end up in the classpath more than once.

In such an application the class loader will pick up the first one found when looking for that class. Once it has found it, this class is loaded and initialized by this class loader, and he will not look it up again. Usually that does not lead to problems, and you will still have the singleton as you want: one instance only.

If - for some reason - you have multiple class loaders at hand, they each could load this class from another location. So you could end with several singleton instances.

The shade plugin seems not to be the best tool for that. I would suggest to use it only for standalone applications that you package in a single shaded JAR - the end product.

We always use the assembly plugin because it gives a more fine-grained control over the packaged assembly. But you should not use shaded JARs as dependencies, instead simply use the core libraries. Even if you have the same dependency in various dependency paths in your project, the assembly plugin will package it only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM