Sub topic 3
Decoupling Java Applications with Services
This chapter assumes you know packages, interfaces, javac, java, JAR files, and basic reflection. A service is an interface whose implementation is selected at runtime. JPMS connects services without making the consumer depend on a provider's module.
Uses and provides
The consumer declares uses. The provider declares provides ... with. The service interface must be exported.
// com.example.greeter/module-info.java
module com.example.greeter {
exports com.example.greeter.api;
uses com.example.greeter.api.GreetingProvider;
}
// com.example.greeter.french/module-info.java
module com.example.greeter.french {
requires com.example.greeter;
provides com.example.greeter.api.GreetingProvider
with com.example.greeter.french.FrenchGreeting;
}
// Consumer code
ServiceLoader<GreetingProvider> providers =
ServiceLoader.load(GreetingProvider.class);
for (GreetingProvider provider : providers) {
System.out.println(provider.greet("monde"));
}Classpath and automatic modules
Classpath classes belong to the unnamed module. They can read named modules, but named modules cannot read the unnamed module. This makes classpath code useful during migration, but it provides little dependency or encapsulation checking.
A JAR placed on the module path without module-info.class becomes an automatic module. Its name comes from the manifest or JAR filename. It reads every observable named module and exports all its packages. Use it as a migration bridge, not as a final design.
Split packages and migration
A split package exists when two named modules contain the same package. JPMS rejects this arrangement because package ownership becomes ambiguous. Merge the packages into one module, rename one package, or keep the legacy code on the classpath temporarily.
A practical migration sequence is:
- Run
jdeps --print-module-deps app.jarto identify JDK module dependencies. - Add a descriptor and move the application to the module path.
- Convert dependencies into named modules, using automatic modules temporarily.
- Remove split packages and replace reflective access with
openswhere needed. - Test both compilation and runtime resolution.
Runtime images and module layers
Use jlink to build a smaller runtime containing only selected modules:
jlink --module-path "$JAVA_HOME/jmods:out" \
--add-modules com.example.app \
--launcher app=com.example.app/com.example.app.Main \
--output image
image/bin/appA module layer is a runtime graph of modules that can be created separately from the boot layer. Frameworks use layers and ModuleLayer.defineModulesWithOneLoader to load plugins dynamically while controlling their readability.
Exercise
Why is an automatic module a temporary migration aid rather than a strong module boundary?
Show answer
It exports all packages and reads every observable module, so it gives weaker encapsulation and dependency control than an explicit descriptor.