Service Provider Interface (SPI) learning example in Java. This example uses SPI to load different ID providers.
Added a simple Service Provider Interface (SPI) example that provides identifier strings.
- Interface:
com.bhf.learning.spi.IdentifierProvider - Providers:
com.bhf.learning.spi.impl.RandomUuidProvider— returns a random UUID stringcom.bhf.learning.spi.impl.TimestampIdProvider— returns a timestamp-based id
The service descriptor is located at src/main/resources/META-INF/services/com.bhf.learning.spi.IdentifierProvider.
Run the tests to see ServiceLoader discover the implementations:
./gradlew testYou can also load providers at runtime using ServiceLoader.load(com.bhf.learning.spi.IdentifierProvider.class).
The project includes com.bhf.learning.spi.IdentifierProviderFactory which selects a provider by configuration. Providers expose a stable name() value (recommended) — current providers provide these names:
uuid—RandomUuidProvidertimestamp—TimestampIdProvider
Selection order used by the factory:
- System property
identifier.provider(e.g.-Didentifier.provider=timestamp) - Environment variable
IDENTIFIER_PROVIDER - First provider discovered by
ServiceLoader(fallback)
The configured value matches either name() (case-insensitive), the simple class name, or the full class name.
Examples:
Run with system property (Gradle):
./gradlew run --no-daemon --console=plain -Didentifier.provider=timestampRun with environment variable:
IDENTIFIER_PROVIDER=uuid ./gradlew run --no-daemon --console=plainProgrammatic usage:
IdentifierProvider p = IdentifierProviderFactory.loadFromConfig();
System.out.println(p.name() + " -> " + p.id());Build, run the sample applications, or run tests with the Gradle wrapper (recommended):
# Run the test suite
./gradlew test