Search code examples
javaspiserviceloader

Getting a simple ServiceLoader to work in Java using 2 supplementary Modules


I am fairly new to using ServiceLoader and I am trying to get a very simple example up and running.

Currently have 4 Modules: BLCore, BLInterface, BLMod1, BLMod2

BLCore depends on: BLInterface, BLMod1, BLMod2
BLInterface depends on: Nonne
BLMod1 depends on: BLInterface
BLMod2 depends on: BLInterface

BLCore contains the main method and contains the following:

import java.util.ServiceLoader;

public class Main {
    public static void main(String[] args) {
        for(BeanInterface val : ServiceLoader.load(BeanInterface.class)){
            System.out.println("You are a "+val.getName());
        }
    }
}

And BLInterface has a single String method that just prints out a name or so.

The structure is as follows:

The code can compile but the ServiceLoader does not detect Module1 and Module2, any ideas?

----STATUS---- All errors removed, still not working.


Solution

  • You should use package rather than the default package. For example com.example.

    In Java 8 (excluding problems due to module):

    • In BLMod1 project, META-INF/services/com.example.BeanInterface must contains com.example.Module1
    • In BLMod2 project, META-INF/services/com.example.BeanInterface must contains com.example.Module2
    • In BLCore configuration (Maven, Gradle or even your IDE), you must ensure to reference the BLMod1 and BLMod2: it must be available in the class path when you execute your main.
    • Be sure that Module1 and Module2 have a public constructor.

    If you are using Java 9++, you may also have to add appropriate line to your module-info.java:

    module com.example.module1 {      
      provides com.example.BeanInterface
          with com.example.Module1;
    }
    

    That's where the package will be useful: you probably can't use modules without a proper package.

    You may also want to read the Javadoc for that: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ServiceLoader.html