Skip to content

bhf/st-learning-java-spi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

StayTuned

st-learning-spi

Service Provider Interface (SPI) learning example in Java. This example uses SPI to load different ID providers.

SPI Example: IdentifierProvider

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 string
    • com.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 test

You can also load providers at runtime using ServiceLoader.load(com.bhf.learning.spi.IdentifierProvider.class).

Configuration-based selection

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:

  • uuidRandomUuidProvider
  • timestampTimestampIdProvider

Selection order used by the factory:

  1. System property identifier.provider (e.g. -Didentifier.provider=timestamp)
  2. Environment variable IDENTIFIER_PROVIDER
  3. 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=timestamp

Run with environment variable:

IDENTIFIER_PROVIDER=uuid ./gradlew run --no-daemon --console=plain

Programmatic usage:

IdentifierProvider p = IdentifierProviderFactory.loadFromConfig();
System.out.println(p.name() + " -> " + p.id());

Running Tests

Build, run the sample applications, or run tests with the Gradle wrapper (recommended):

# Run the test suite
./gradlew test

About

st-learning: Java SPI (service provider interface) example

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages