I came across a recent blog entry about using ServiceLoader in a modular environment:

  https://blog.frankel.ch/migrating-serviceloader-java-9-module-system/

Unfortunately, it is completely wrong in its advice on "Migrating to the Java Platform Module System". I have seen the same bad advice on StackOverflow, so let me correct it here, as simply as possible:

1. The module containing the implementation SHOULD NOT export the implementation package.

2. The module containing the client MUST say that it uses the service interface.

See the "Deploying service providers as modules" section of https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/ServiceLoader.html

The whole point of integrating ServiceLoader with the module system was get the configuration documented explicitly, via `uses` and `provides` clauses. Benefits: the implementation is strongly encapsulated (no `exports`), and the client's service lookup is speedy because its dependency (`uses`) was found cheaply during startup. Eventually, as the blog rightly says, "only the configuration changes: the Service Loader code itself in the client doesn’t change."

Alex

Reply via email to