Demonstrating the use of the serviceloader-maven-plugin
for seamless ServiceLoader
auto service discovery in a Maven multi-module project.
I fell back to this after failing to make the conventional JDK service auto discovery work as expected in a multi-module Maven project
Defines the TextService
interface.
public interface TextService {
String process(String text);
}
Implements UpperCaseTextService
, transforming text to uppercase.
public class UpperCaseTextService implements TextService {
@Override
public String process(String text) {
return text == null ? null : text.toUpperCase();
}
}
Configures Maven build for the consumer
module as a service consumer, dynamically discovering implementations.
<!-- consumer/pom.xml -->
<!-- Dependencies -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>service</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>provider</artifactId>
<version>${project.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Properties -->
<properties>
<exec.mainClass>com.github.idelstak.consumer.Consumer</exec.mainClass>
<deps.dir>libs</deps.dir>
</properties>
<!-- Build Plugins -->
<build>
<plugins>
<!-- maven-compiler-plugin -->
<!-- maven-dependency-plugin -->
<!-- maven-jar-plugin -->
</plugins>
</build>
provider
module: Runtime dependency for dynamic service discovery. Scope set toruntime
to avoid compile-time transitive dependencies.
Runtime dependency on
provider
is crucial for ServiceLoader to dynamically discover and loadTextService
implementations during execution.
Configures the serviceloader-maven-plugin
at the parent level for effective service discovery across modules.