Skip to content

Commit

Permalink
add ComponentLoader to support more auto configuration scenarios, e.g…
Browse files Browse the repository at this point in the history
…. spring boot
  • Loading branch information
zeitlinger committed Feb 9, 2024
1 parent 1a6f001 commit b2539b2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/** A loader for components that are discovered via SPI. */
public interface ComponentLoader {
<T> Iterable<T> load(Class<T> spiClass);

default <T> Optional<T> loadOptional(Class<T> spiClass) {
Iterable<T> iterable = load(spiClass);
return StreamSupport.stream(iterable.spliterator(), false).findFirst();
}

/**
* Load implementations of an ordered SPI (i.e. implements {@link Ordered}).
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,7 @@ public <T, S extends ConfigurableProvider> NamedSpiManager<T> loadConfigurable(
// both the provider and the result may have a listener
maybeAddListener(provider);

nameToProvider.put(
name,
() -> {
T result = getConfigurable.apply(provider, config);
maybeAddListener(result);
return result;
});
nameToProvider.put(name, () -> maybeAddListener(getConfigurable.apply(provider, config)));
}
return NamedSpiManager.create(nameToProvider);
}
Expand Down Expand Up @@ -111,32 +105,27 @@ public <T> List<T> load(Class<T> spiClass) {
private <T> List<T> init(Iterable<T> components) {
List<T> result = new ArrayList<>();
for (T service : components) {
maybeAddListener(service);
result.add(service);
result.add(maybeAddListener(service));
}
return result;
}

public <T> Optional<T> loadOptional(Class<T> spiClass) {
return load(spiClass).stream().findFirst();
return componentLoader.loadOptional(spiClass).map(this::maybeAddListener);
}

private void maybeAddListener(Object object) {
private <T> T maybeAddListener(T object) {
if (object instanceof AutoConfigureListener) {
listeners.add((AutoConfigureListener) object);
}
return object;
}

/** Return the set of SPIs loaded which implement {@link AutoConfigureListener}. */
public Set<AutoConfigureListener> getListeners() {
return Collections.unmodifiableSet(listeners);
}

// Visible for testing
interface SpiFinder {
<T> Iterable<T> load(Class<T> spiClass, ClassLoader classLoader);
}

private static class ServiceLoaderComponentLoader implements ComponentLoader {
private final ClassLoader classLoader;

Expand Down

0 comments on commit b2539b2

Please sign in to comment.