Search in sources :

Example 16 with Key

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

the class PrivateElementsImpl method applyTo.

@Override
public void applyTo(Binder binder) {
    PrivateBinder privateBinder = binder.withSource(source).newPrivateBinder();
    for (Element element : getElements()) {
        element.applyTo(privateBinder);
    }
    // ensure exposedKeysToSources is populated
    getExposedKeys();
    for (Map.Entry<Key<?>, Object> entry : exposedKeysToSources.entrySet()) {
        privateBinder.withSource(entry.getValue()).expose(entry.getKey());
    }
}
Also used : PrivateBinder(com.google.inject.PrivateBinder) Element(com.google.inject.spi.Element) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) Key(com.google.inject.Key)

Example 17 with Key

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

the class InjectorImpl method createJustInTimeBinding.

/**
   * Returns a new just-in-time binding created by resolving {@code key}. The strategies used to
   * create just-in-time bindings are:
   *
   * <ol>
   * <li>Internalizing Providers. If the requested binding is for {@code Provider<T>}, we delegate
   *     to the binding for {@code T}.
   * <li>Converting constants.
   * <li>ImplementedBy and ProvidedBy annotations. Only for unannotated keys.
   * <li>The constructor of the raw type. Only for unannotated keys.
   * </ol>
   *
   * @throws com.google.inject.internal.ErrorsException if the binding cannot be created.
   */
private <T> BindingImpl<T> createJustInTimeBinding(Key<T> key, Errors errors, boolean jitDisabled, JitLimitation jitType) throws ErrorsException {
    int numErrorsBefore = errors.size();
    // Retrieve the sources before checking for blacklisting to guard against sources becoming null
    // due to a full GC happening after calling state.isBlacklisted and
    // state.getSourcesForBlacklistedKey.
    // TODO(user): Consolidate these two APIs.
    Set<Object> sources = state.getSourcesForBlacklistedKey(key);
    if (state.isBlacklisted(key)) {
        throw errors.childBindingAlreadySet(key, sources).toException();
    }
    // Handle cases where T is a Provider<?>.
    if (isProvider(key)) {
        // These casts are safe. We know T extends Provider<X> and that given Key<Provider<X>>,
        // createProviderBinding() will return BindingImpl<Provider<X>>.
        @SuppressWarnings({ "unchecked", "cast" }) BindingImpl<T> binding = (BindingImpl<T>) createProviderBinding((Key) key, errors);
        return binding;
    }
    // Handle cases where T is a MembersInjector<?>
    if (isMembersInjector(key)) {
        // These casts are safe. T extends MembersInjector<X> and that given Key<MembersInjector<X>>,
        // createMembersInjectorBinding() will return BindingImpl<MembersInjector<X>>.
        @SuppressWarnings({ "unchecked", "cast" }) BindingImpl<T> binding = (BindingImpl<T>) createMembersInjectorBinding((Key) key, errors);
        return binding;
    }
    // Try to convert a constant string binding to the requested type.
    BindingImpl<T> convertedBinding = convertConstantStringBinding(key, errors);
    if (convertedBinding != null) {
        return convertedBinding;
    }
    if (!isTypeLiteral(key) && jitDisabled && jitType != JitLimitation.NEW_OR_EXISTING_JIT) {
        throw errors.jitDisabled(key).toException();
    }
    // If the key has an annotation...
    if (key.getAnnotationType() != null) {
        // Look for a binding without annotation attributes or return null.
        if (key.hasAttributes() && !options.exactBindingAnnotationsRequired) {
            try {
                Errors ignored = new Errors();
                return getBindingOrThrow(key.withoutAttributes(), ignored, JitLimitation.NO_JIT);
            } catch (ErrorsException ignored) {
            // throw with a more appropriate message below
            }
        }
        throw errors.missingImplementationWithHint(key, this).toException();
    }
    Object source = key.getTypeLiteral().getRawType();
    BindingImpl<T> binding = createUninitializedBinding(key, Scoping.UNSCOPED, source, errors, true);
    errors.throwIfNewErrors(numErrorsBefore);
    initializeJitBinding(binding, errors);
    return binding;
}
Also used : InjectionPoint(com.google.inject.spi.InjectionPoint) Key(com.google.inject.Key)

Example 18 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class PrivateElementsImpl method applyTo.

public void applyTo(Binder binder) {
    PrivateBinder privateBinder = binder.withSource(source).newPrivateBinder();
    for (Element element : getElements()) {
        element.applyTo(privateBinder);
    }
    // ensure exposedKeysToSources is populated
    getExposedKeys();
    for (Map.Entry<Key<?>, Object> entry : exposedKeysToSources.entrySet()) {
        privateBinder.withSource(entry.getValue()).expose(entry.getKey());
    }
}
Also used : PrivateBinder(com.google.inject.PrivateBinder) Element(com.google.inject.spi.Element) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) Key(com.google.inject.Key)

Example 19 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class BinderTest method testArrayTypeCanonicalization.

/**
   * Although {@code String[].class} isn't equal to {@code new
   * GenericArrayTypeImpl(String.class)}, Guice should treat these two types
   * interchangeably.
   */
public void testArrayTypeCanonicalization() {
    final String[] strings = new String[] { "A" };
    final Integer[] integers = new Integer[] { 1 };
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(String[].class).toInstance(strings);
            bind(new TypeLiteral<Integer[]>() {
            }).toInstance(integers);
        }
    });
    assertSame(integers, injector.getInstance(Key.get(new TypeLiteral<Integer[]>() {
    })));
    assertSame(integers, injector.getInstance(new Key<Integer[]>() {
    }));
    assertSame(integers, injector.getInstance(Integer[].class));
    assertSame(strings, injector.getInstance(Key.get(new TypeLiteral<String[]>() {
    })));
    assertSame(strings, injector.getInstance(new Key<String[]>() {
    }));
    assertSame(strings, injector.getInstance(String[].class));
    try {
        Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {
                bind(String[].class).toInstance(new String[] { "A" });
                bind(new TypeLiteral<String[]>() {
                }).toInstance(new String[] { "B" });
            }
        });
        fail();
    } catch (CreationException expected) {
        assertContains(expected.getMessage(), "1) A binding to java.lang.String[] was already configured at " + getClass().getName(), "at " + getClass().getName(), getDeclaringSourcePart(getClass()));
        assertContains(expected.getMessage(), "1 error");
    }
    // passes because duplicates are ignored
    injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(String[].class).toInstance(strings);
            bind(new TypeLiteral<String[]>() {
            }).toInstance(strings);
        }
    });
    assertSame(strings, injector.getInstance(Key.get(new TypeLiteral<String[]>() {
    })));
    assertSame(strings, injector.getInstance(new Key<String[]>() {
    }));
    assertSame(strings, injector.getInstance(String[].class));
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) CreationException(com.google.inject.CreationException) Key(com.google.inject.Key) AbstractModule(com.google.inject.AbstractModule)

Example 20 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class ServletScopesTest method testIsRequestScopedNegative.

public void testIsRequestScopedNegative() {
    final Key<String> a = Key.get(String.class, named("A"));
    final Key<String> b = Key.get(String.class, named("B"));
    final Key<String> c = Key.get(String.class, named("C"));
    final Key<String> d = Key.get(String.class, named("D"));
    final Key<String> e = Key.get(String.class, named("E"));
    final Key<String> f = Key.get(String.class, named("F"));
    final Key<String> g = Key.get(String.class, named("G"));
    final Key<String> h = Key.get(String.class, named("H"));
    final Key<String> i = Key.get(String.class, named("I"));
    final Key<String> j = Key.get(String.class, named("J"));
    Module requestScopedBindings = new AbstractModule() {

        @Override
        protected void configure() {
            bind(a).to(b);
            bind(b).to(c);
            bind(c).toProvider(Providers.of("c")).in(Scopes.NO_SCOPE);
            bind(d).toInstance("d");
            bind(e).toProvider(Providers.of("e")).asEagerSingleton();
            bind(f).toProvider(Providers.of("f")).in(Scopes.SINGLETON);
            bind(g).toProvider(Providers.of("g")).in(Singleton.class);
            bind(h).toProvider(Providers.of("h")).in(CustomScoped.class);
            bindScope(CustomScoped.class, Scopes.NO_SCOPE);
            install(new PrivateModule() {

                @Override
                protected void configure() {
                    bind(i).toProvider(Providers.of("i")).in(CustomScoped.class);
                    expose(i);
                }
            });
        }

        @Provides
        @Named("J")
        @CustomScoped
        String provideJ() {
            return "j";
        }
    };
    // we know the module contains only bindings
    @SuppressWarnings("unchecked") List<Element> moduleBindings = Elements.getElements(requestScopedBindings);
    ImmutableMap<Key<?>, Binding<?>> map = indexBindings(moduleBindings);
    assertFalse(ServletScopes.isRequestScoped(map.get(a)));
    assertFalse(ServletScopes.isRequestScoped(map.get(b)));
    assertFalse(ServletScopes.isRequestScoped(map.get(c)));
    assertFalse(ServletScopes.isRequestScoped(map.get(d)));
    assertFalse(ServletScopes.isRequestScoped(map.get(e)));
    assertFalse(ServletScopes.isRequestScoped(map.get(f)));
    assertFalse(ServletScopes.isRequestScoped(map.get(g)));
    assertFalse(ServletScopes.isRequestScoped(map.get(h)));
    assertFalse(ServletScopes.isRequestScoped(map.get(i)));
    assertFalse(ServletScopes.isRequestScoped(map.get(j)));
    Injector injector = Guice.createInjector(requestScopedBindings);
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(a)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(b)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(c)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(d)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(e)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(f)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(g)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(h)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(i)));
    assertFalse(ServletScopes.isRequestScoped(injector.getBinding(j)));
}
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) PrivateModule(com.google.inject.PrivateModule) AbstractModule(com.google.inject.AbstractModule) PrivateModule(com.google.inject.PrivateModule) Key(com.google.inject.Key)

Aggregations

Key (com.google.inject.Key)106 AbstractModule (com.google.inject.AbstractModule)55 Injector (com.google.inject.Injector)52 Binding (com.google.inject.Binding)36 Module (com.google.inject.Module)20 Provider (com.google.inject.Provider)18 Element (com.google.inject.spi.Element)16 Map (java.util.Map)16 HasDependencies (com.google.inject.spi.HasDependencies)14 InstanceBinding (com.google.inject.spi.InstanceBinding)13 List (java.util.List)13 TypeLiteral (com.google.inject.TypeLiteral)12 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)10 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)9 PrivateModule (com.google.inject.PrivateModule)8 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)8 Dependency (com.google.inject.spi.Dependency)8 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)8 ImmutableList (com.google.common.collect.ImmutableList)7 InjectionPoint (com.google.inject.spi.InjectionPoint)7