Created
July 30, 2019 18:21
-
-
Save jezperyo/59bf9abf99a0a4a9466e9051f1565035 to your computer and use it in GitHub Desktop.
guice combined injectors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.inject.*; | |
import com.google.inject.spi.Elements; | |
import java.util.Arrays; | |
import java.util.logging.Logger; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Example { | |
public static void main(final String... args) { | |
final Injector firstInjector = newExampleInjector(String.class, "hello"); | |
final Injector secondInjector = newExampleInjector(Integer.class, 1337); | |
final Injector combinedInjector = combined(firstInjector, secondInjector); | |
System.out.println("Bindings: "); | |
combinedInjector.getAllBindings().values() | |
.stream() | |
.filter(Example::isNotFrameworkType) | |
.forEach(System.out::println); | |
} | |
private static <T> Injector newExampleInjector(final Class<T> tClass, final T instance) { | |
return Guice.createInjector(new AbstractModule() { | |
@Override | |
protected void configure() { | |
bind(tClass).toInstance(instance); | |
} | |
}); | |
} | |
private static Injector combined(boolean withParents, final Injector... injectors) { | |
return Guice.createInjector(Elements.getModule(Arrays.stream(injectors) | |
.flatMap(i -> collectBindings(withParents, i)) | |
.filter(Example::isNotFrameworkType) | |
.collect(Collectors.toList()))); | |
} | |
private static Injector combined(final Injector... injectors) { | |
return combined(false, injectors); | |
} | |
private static Stream<Binding<?>> collectBindings(final boolean withParents, Injector injector) { | |
final Stream.Builder<Binding<?>> builder = Stream.builder(); | |
while (injector != null) { | |
injector.getAllBindings().values().forEach(builder); | |
injector = withParents ? injector.getParent() : null; | |
} | |
return builder.build(); | |
} | |
private static boolean isNotFrameworkType(final Binding<?> value) { | |
final Class<?> type = value.getKey().getTypeLiteral().getRawType(); | |
return Stream.of(Stage.class, Injector.class, Logger.class).noneMatch(c -> c.isAssignableFrom(type)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment