Create a new source folder with the location src/main/resources
, then create your META-INF/services
folder in there and drop in your fully-qualified class name (FQCN) file. This should copy them into the jar file automatically. So for implementations of an interface with a FQCN of com.acme.MyInterface
, you’ll have:
Project
| src
| | main
| | java
| | [your source code]
| | resources
| | META-INF
| | services
| | com.acme.MyInterface
Note that com.acme.MyInterface
is the name of the file, not a directory structure like a Java package. The name of the file is the FQCN of the interface that you’re implementing, and in it, you’ll have the FQCN of each implementation on its own line, e.g.:
com.example.MyInterfaceImpl
com.example.AnotherMyInterfaceImpl
It’s worth noting that this applies to Gradle projects with the default source sets as well.
Once you do this, you can load all the implementations of the interface using ServiceLoader
:
ServiceLoader<MyInterface> loader = ServiceLoader.load(MyInterface.class);
for (MyInterface service : loader) {
// Prints com.example.MyInterfaceImpl and com.example.AnotherMyInterfaceImpl
System.out.println(service.class.getName());
}
Some things to note:
- All the implementations must have a no-args constructor
- Applications that use modules or custom classloaders may have to use the overloads of
ServiceLoader.load
If these conditions won’t work for you, then you may want to switch to another system, e.g. a CDI-style framework like Spring, EJB, etc.