package net.pterodactylus.util.inject;
+import com.google.inject.Key;
import com.google.inject.Module;
+import com.google.inject.name.Names;
+
+import static com.google.inject.name.Names.named;
/**
* Helper class for Guice configuration.
return (binder) -> binder.bind(requestedClass).toInstance(instance);
}
+ public $2<T> named(String name) {
+ return new $2<>(requestedClass, name);
+ }
+
+ }
+
+ public static class $2<T> {
+
+ private $2(Class<T> requestedClass, String name) {
+ this.requestedClass = requestedClass;
+ this.name = name;
+ }
+
+ public Module is(T instance) {
+ return (binder) -> binder.bind(Key.get(requestedClass, named(name))).toInstance(instance);
+ }
+
+ private final Class<T> requestedClass;
+ private final String name;
+
}
}
package net.pterodactylus.util.inject;
-import com.google.inject.Guice;
+import com.google.inject.ConfigurationException;
import com.google.inject.Injector;
-import org.hamcrest.MatcherAssert;
-import org.hamcrest.Matchers;
+import com.google.inject.Key;
+import com.google.inject.name.Names;
import org.junit.jupiter.api.Test;
+import static com.google.inject.Guice.createInjector;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* Unit test for {@link ObjectBinding}.
*
@Test
public void objectIsBound() {
TestClass testObject = new TestClass();
- Injector injector = Guice.createInjector(ObjectBinding.forClass(TestInterface.class).is(testObject));
- MatcherAssert.assertThat(injector.getInstance(TestInterface.class), Matchers.sameInstance(testObject));
+ Injector injector = createInjector(ObjectBinding.forClass(TestInterface.class).is(testObject));
+ assertThat(injector.getInstance(TestInterface.class), sameInstance(testObject));
}
- public interface TestInterface { }
+ @Test
+ public void namedObjectIsBound() {
+ TestClass testObject = new TestClass();
+ Injector injector = createInjector(ObjectBinding.forClass(TestInterface.class).named("foo").is(testObject));
+ assertThat(injector.getInstance(Key.get(TestInterface.class, Names.named("foo"))), sameInstance(testObject));
+ }
- public static class TestClass implements TestInterface { }
+ @Test
+ public void namedObjectIsNotReturnedIfNotAskedForByName() {
+ TestClass testObject = new TestClass();
+ Injector injector = createInjector(ObjectBinding.forClass(TestInterface.class).named("foo").is(testObject));
+ assertThrows(ConfigurationException.class, () -> injector.getInstance(TestInterface.class));
+ }
+
+ public interface TestInterface {
+ }
+
+ public static class TestClass implements TestInterface {
+ }
}