When to use the ServiceLoader class in a module in Java 9?


Java has a ServiceLoader class from java.util package that can help to locate service providers at the runtime by searching in the classpath. For service providers defined in modules, we can look at the sample application to declare modules with service and how it works.

For instance, we have a "test.app" module that we need to use Logger that can be retrieved from System.getLogger() factory method with the help of LoggerFinder service.

module com.tutorialspoint.test.app {
   requires java.logging;
   exports com.tutorialspoint.platformlogging.app;
   uses java.lang.System.LoggerFinder;
}

Below is the test.app.MainApp class:

package com.tutorialspoint.platformlogging.app;

public class MainApp {
   private static Logger LOGGER = System.getLogger();
   public static void main(String args[]) {
      LOGGER.log();
   }
}


This is LoggerFinder implementation inside the "test.logging" module:

package com.tutorialspoint.platformlogging.logger;

public class MyLoggerFinder extends LoggerFinder {
   @Override
   public Logger getLogger(String name, Module module) {
      // return a Logger depending on name/module
   }
}

In "test.logging" module declaration, we can provide an implementation of LoggerFinder service with a "provides – with" clause. 

module com.tutorialspoint.test.logging {
   provides java.lang.System.LoggerFinder
   with com.tutorialspoint.platformlogging.logger.MyLoggerFinder;
}

Updated on: 09-Apr-2020

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements