今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

标签:#serviceloader

找到 1 篇相关文章

开发者

Making ServiceLoader usable: a provider factory

I keep coming back to java.util.ServiceLoader . I have used it to put a JSON layer behind a contract, so the core code carries no direct dependency on any particular JSON library and I can swap the implementation without touching callers. The same shape works for JWT handling, where the concrete library might be jose4j or another JOSE implementation, and you can easily find other decoupling use-cases. The motivation is always the same: the application should depend on a capability, not on a vendor. A while back I wrote about exactly that idea in Rediscovering Java ServiceLoader: Beyond Plugins and Into Capabilities , where the argument was to treat ServiceLoader as capability discovery rather than a plugin system. That piece hit the limitation everyone hits — the no-argument constructor — and worked around it with a default constructor plus a dynamic proxy that built the real object through a factory on each call. It works, but it is indirection bolted on after the fact, not a design. This post is the part I never pinned down back then: turning that workaround into a small, explicit pattern. The running example below is a mock payments system, with Stripe and PayPal specializations, because it is compact enough to show end to end. The JSON and JWT cases cited can be built with the same structure. The two limits ServiceLoader leaves you The first is the no-argument constructor. Whatever ServiceLoader instantiates must have a public, parameterless constructor. My StripePaymentService takes an API key, so it cannot be the class ServiceLoader loads — not unless I bolt on some init-after-construction step, which I would rather avoid. The second is selection, or rather the lack of it. ServiceLoader gives you every implementation it finds, in roughly classpath order. There is no id, nothing to prioritise on, and no way to ask whether a given one even applies in the current environment. With two backends on the classpath and only one configured, working out which to use is

2026-07-14 原文 →