druvu-lib-loader
A type-safe component loading system built on top of Java’s ServiceLoader mechanism.
Overview
druvu-lib-loader provides dependency injection and singleton management through factories, with particular suitability for Java Platform Module System (JPMS) applications. It wraps Java’s native ServiceLoader with additional type safety and lifecycle management.
Quick Example
Here’s a real-world example showing how to create a pluggable accounting book loader:
1. Define your API interface:
public interface AccBook {
String id();
List<Account> accounts();
}
2. Create a static factory method:
public interface AccBookFactory {
static AccBook load(Path path) {
return ComponentLoader.load(AccBook.class,
Dependencies.of(Path.class, path));
}
}
3. Implement ComponentFactory in your implementation module:
public class GnucashBookFactory implements ComponentFactory<AccBook> {
@Override
public AccBook createComponent(Dependencies dependencies) {
var path = dependencies.getOptionalDependency(Path.class)
.orElseThrow(() -> new IllegalArgumentException(
"Path dependency required"));
return new GnucashAccBook(path);
}
@Override
public Class<AccBook> getComponentType() {
return AccBook.class;
}
}
4. Register the factory:
For non-JPMS, create META-INF/services/com.druvu.lib.loader.ComponentFactory:
com.myapp.gnucash.io.GnucashBookFactory
For JPMS, add to module-info.java:
provides com.druvu.lib.loader.ComponentFactory
with com.myapp.gnucash.io.GnucashBookFactory;
5. Use it:
AccBook book = AccBookFactory.load(Paths.get("/path/to/file.xml"));
Core Loaders
| Loader | Purpose |
|---|---|
| ComponentLoader | Single implementation; fails if multiple exist |
| MultiComponentLoader | All implementations; returns empty list if none found |
| SingletonLoader | Application-wide services with two-phase initialization |
Installation
Maven:
<dependency>
<groupId>com.druvu</groupId>
<artifactId>druvu-lib-loader</artifactId>
<version>1.0.7</version>
</dependency>
Gradle:
implementation 'com.druvu:druvu-lib-loader:1.0.7'
Design Principles
- Thread-safe synchronization on target classes
- Fail-fast exception throwing
- Compile-time type checking via generics
- Immutable dependency containers
License
Apache License 2.0