Search in sources :

Example 56 with Binding

use of com.google.inject.Binding in project guice by google.

the class MultibinderTest method testSetAndMapValueAreDistinctInSpi.

// See issue 670
public void testSetAndMapValueAreDistinctInSpi() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder.newSetBinder(binder(), String.class).addBinding().toInstance("A");
            MapBinder.newMapBinder(binder(), String.class, String.class).addBinding("B").toInstance("b");
            OptionalBinder.newOptionalBinder(binder(), String.class).setDefault().toInstance("C");
        }
    });
    Collector collector = new Collector();
    Binding<Map<String, String>> mapbinding = injector.getBinding(Key.get(mapOfStringString));
    mapbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.mapbinding);
    Binding<Set<String>> setbinding = injector.getBinding(Key.get(setOfString));
    setbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.setbinding);
    Binding<Optional<String>> optionalbinding = injector.getBinding(Key.get(optionalOfString));
    optionalbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.optionalbinding);
    // There should only be three instance bindings for string types
    // (but because of the OptionalBinder, there's 2 ProviderInstanceBindings also).
    // We also know the InstanceBindings will be in the order: A, b, C because that's
    // how we bound them, and binding order is preserved.
    List<Binding<String>> bindings = FluentIterable.from(injector.findBindingsByType(stringType)).filter(Predicates.instanceOf(InstanceBinding.class)).toList();
    assertEquals(bindings.toString(), 3, bindings.size());
    Binding<String> a = bindings.get(0);
    Binding<String> b = bindings.get(1);
    Binding<String> c = bindings.get(2);
    assertEquals("A", ((InstanceBinding<String>) a).getInstance());
    assertEquals("b", ((InstanceBinding<String>) b).getInstance());
    assertEquals("C", ((InstanceBinding<String>) c).getInstance());
    // Make sure the correct elements belong to their own sets.
    assertFalse(collector.mapbinding.containsElement(a));
    assertTrue(collector.mapbinding.containsElement(b));
    assertFalse(collector.mapbinding.containsElement(c));
    assertTrue(collector.setbinding.containsElement(a));
    assertFalse(collector.setbinding.containsElement(b));
    assertFalse(collector.setbinding.containsElement(c));
    assertFalse(collector.optionalbinding.containsElement(a));
    assertFalse(collector.optionalbinding.containsElement(b));
    assertTrue(collector.optionalbinding.containsElement(c));
}
Also used : Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) Optional(com.google.common.base.Optional) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 57 with Binding

use of com.google.inject.Binding in project guice by google.

the class MultibinderTest method testKeyHashCodesFixedAtInjectionTime.

/** Ensure key hash codes are fixed at injection time, not binding time. */
public void testKeyHashCodesFixedAtInjectionTime() {
    Module ab = new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings);
            List<String> list = Lists.newArrayList();
            multibinder.addBinding().toInstance(list);
            list.add("A");
            list.add("B");
        }
    };
    Injector injector = Guice.createInjector(ab);
    for (Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
        Key<?> bindingKey = entry.getKey();
        Key<?> clonedKey;
        if (bindingKey.getAnnotation() != null) {
            clonedKey = Key.get(bindingKey.getTypeLiteral(), bindingKey.getAnnotation());
        } else if (bindingKey.getAnnotationType() != null) {
            clonedKey = Key.get(bindingKey.getTypeLiteral(), bindingKey.getAnnotationType());
        } else {
            clonedKey = Key.get(bindingKey.getTypeLiteral());
        }
        assertEquals(bindingKey, clonedKey);
        assertEquals("Incorrect hashcode for " + bindingKey + " -> " + entry.getValue(), bindingKey.hashCode(), clonedKey.hashCode());
    }
}
Also used : Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) Injector(com.google.inject.Injector) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) Key(com.google.inject.Key) AbstractModule(com.google.inject.AbstractModule)

Example 58 with Binding

use of com.google.inject.Binding in project guice by google.

the class MapBinderTest method testAllBindings.

public void testAllBindings() {
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            MapBinder.newMapBinder(binder(), String.class, String.class).permitDuplicates();
        }
    };
    Injector injector = Guice.createInjector(module);
    Map<Key<?>, Binding<?>> bindings = injector.getBindings();
    ImmutableSet<Key<?>> expectedBindings = ImmutableSet.<Key<?>>builder().add(// Map<K, V>
    Key.get(Types.mapOf(String.class, String.class)), // Map<K, Provider<V>>
    Key.get(Types.mapOf(String.class, Types.providerOf(String.class))), // Map<K, javax.inject.Provider<V>>
    Key.get(Types.mapOf(String.class, javaxProviderOf(String.class))), // Map<K, Set<V>>
    Key.get(Types.mapOf(String.class, Types.setOf(String.class))), // Map<K, Set<Provider<V>>
    Key.get(Types.mapOf(String.class, Types.setOf(Types.providerOf(String.class)))), // Map<K, Set<javax.inject.Provider<V>>
    Key.get(Types.mapOf(String.class, Types.setOf(Types.javaxProviderOf(String.class)))), // Map<K, Collection<Provider<V>>
    Key.get(Types.mapOf(String.class, Types.collectionOf(Types.providerOf(String.class)))), // Map<K, Collection<javax.inject.Provider<V>>
    Key.get(Types.mapOf(String.class, Types.collectionOf(Types.javaxProviderOf(String.class)))), // Set<Map.Entry<K, Provider<V>>>
    Key.get(Types.setOf(mapEntryOf(String.class, Types.providerOf(String.class)))), // Set<Map.Entry<K, javax.inject.Provider<V>>>
    Key.get(Types.setOf(mapEntryOf(String.class, Types.javaxProviderOf(String.class)))), // Collection<Provider<Map.Entry<K, Provider<V>>>>
    Key.get(collectionOf(Types.providerOf(mapEntryOf(String.class, Types.providerOf(String.class))))), // Collection<javax.inject.Provider<Map.Entry<K, Provider<V>>>>
    Key.get(collectionOf(Types.javaxProviderOf(mapEntryOf(String.class, Types.providerOf(String.class))))), // @Named(...) Boolean
    Key.get(Boolean.class, named("Multibinder<java.util.Map$Entry<java.lang.String, " + "com.google.inject.Provider<java.lang.String>>> permits duplicates"))).addAll(FRAMEWORK_KEYS).build();
    Set<Key<?>> missingBindings = Sets.difference(expectedBindings, bindings.keySet());
    Set<Key<?>> extraBindings = Sets.difference(bindings.keySet(), expectedBindings);
    assertTrue("There should be no missing bindings. Missing: " + missingBindings, missingBindings.isEmpty());
    assertTrue("There should be no extra bindings. Extra: " + extraBindings, extraBindings.isEmpty());
}
Also used : ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) MapBinderBinding(com.google.inject.multibindings.MapBinderBinding) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) Key(com.google.inject.Key) AbstractModule(com.google.inject.AbstractModule)

Example 59 with Binding

use of com.google.inject.Binding in project guice by google.

the class ExtensionSpiTest method testSpiOnElements.

public final void testSpiOnElements() throws Exception {
    AssistedInjectSpiVisitor visitor = new AssistedInjectSpiVisitor();
    Integer count = 0;
    for (Element element : Elements.getElements(new Module())) {
        if (element instanceof Binding) {
            assertEquals(count++, ((Binding<?>) element).acceptTargetVisitor(visitor));
        }
    }
    validateVisitor(visitor);
}
Also used : Binding(com.google.inject.Binding) Element(com.google.inject.spi.Element) AbstractModule(com.google.inject.AbstractModule)

Example 60 with Binding

use of com.google.inject.Binding in project guice by google.

the class FactoryModuleBuilderTest method testFactoryBindingDependencies.

public void testFactoryBindingDependencies() {
    // validate dependencies work in all stages & as a raw element,
    // and that dependencies work for methods, fields, constructors,
    // and for @AssistedInject constructors too.
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(42);
            bind(Double.class).toInstance(4.2d);
            bind(Float.class).toInstance(4.2f);
            bind(String.class).annotatedWith(named("dog")).toInstance("dog");
            bind(String.class).annotatedWith(named("cat1")).toInstance("cat1");
            bind(String.class).annotatedWith(named("cat2")).toInstance("cat2");
            bind(String.class).annotatedWith(named("cat3")).toInstance("cat3");
            bind(String.class).annotatedWith(named("arbitrary")).toInstance("fail!");
            install(new FactoryModuleBuilder().implement(Animal.class, Dog.class).build(AnimalHouse.class));
        }
    };
    Set<Key<?>> expectedKeys = ImmutableSet.<Key<?>>of(Key.get(Integer.class), Key.get(Double.class), Key.get(Float.class), Key.get(String.class, named("dog")), Key.get(String.class, named("cat1")), Key.get(String.class, named("cat2")), Key.get(String.class, named("cat3")));
    Injector injector = Guice.createInjector(module);
    validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
    injector = Guice.createInjector(Stage.TOOL, module);
    validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
    List<Element> elements = Elements.getElements(module);
    boolean found = false;
    for (Element element : elements) {
        if (element instanceof Binding) {
            Binding<?> binding = (Binding<?>) element;
            if (binding.getKey().equals(Key.get(AnimalHouse.class))) {
                found = true;
                validateDependencies(expectedKeys, binding);
                break;
            }
        }
    }
    assertTrue(found);
}
Also used : Binding(com.google.inject.Binding) Element(com.google.inject.spi.Element) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) Key(com.google.inject.Key)

Aggregations

Binding (com.google.inject.Binding)92 Injector (com.google.inject.Injector)58 Key (com.google.inject.Key)36 AbstractModule (com.google.inject.AbstractModule)33 InstanceBinding (com.google.inject.spi.InstanceBinding)23 Map (java.util.Map)21 HttpServletRequest (javax.servlet.http.HttpServletRequest)21 Module (com.google.inject.Module)18 Element (com.google.inject.spi.Element)18 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)17 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)16 HttpServlet (javax.servlet.http.HttpServlet)14 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)12 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)12 ServletContext (javax.servlet.ServletContext)12 ImmutableMap (com.google.common.collect.ImmutableMap)11 HashMap (java.util.HashMap)11 TypeLiteral (com.google.inject.TypeLiteral)10 MapBinderBinding (com.google.inject.multibindings.MapBinderBinding)10