Search in sources :

Example 16 with ConfigurationException

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

the class InjectionPointTest method testTooManyConstructors_withOptionalConstructorError.

public void testTooManyConstructors_withOptionalConstructorError() {
    ConfigurationException exception = assertThrows(ConfigurationException.class, () -> InjectionPoint.forConstructorOf(TypeLiteral.get(TooManyConstructorsWithOptional.class)));
    // Verify that both errors are reported in the exception
    assertThat(exception).hasMessageThat().contains("has more than one constructor annotated with @Inject.");
    assertThat(exception).hasMessageThat().contains("TooManyConstructorsWithOptional.<init>() is annotated @Inject(optional=true), but" + " constructors cannot be optional.");
}
Also used : ConfigurationException(com.google.inject.ConfigurationException)

Example 17 with ConfigurationException

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

the class InjectionPointTest method testForConstructorOfRequireAtInject_fail.

public void testForConstructorOfRequireAtInject_fail() {
    ConfigurationException exception = assertThrows(ConfigurationException.class, () -> InjectionPoint.forConstructorOf(TypeLiteral.get(NoArgNonConstructable.class), /* atInjectRequired= */
    true));
    assertThat(exception).hasMessageThat().contains("Injector is configured to require @Inject constructors but class" + " InjectionPointTest$NoArgNonConstructable does not have a @Inject annotated" + " constructor.");
}
Also used : ConfigurationException(com.google.inject.ConfigurationException)

Example 18 with ConfigurationException

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

the class FactoryProvider2 method findMatchingConstructorInjectionPoint.

/**
 * Finds a constructor suitable for the method. If the implementation contained any constructors
 * marked with {@link AssistedInject}, this requires all {@link Assisted} parameters to exactly
 * match the parameters (in any order) listed in the method. Otherwise, if no {@link
 * AssistedInject} constructors exist, this will default to looking for an {@literal @}{@link
 * Inject} constructor.
 */
private <T> InjectionPoint findMatchingConstructorInjectionPoint(Method method, Key<?> returnType, TypeLiteral<T> implementation, List<Key<?>> paramList) throws ErrorsException {
    Errors errors = new Errors(method);
    if (returnType.getTypeLiteral().equals(implementation)) {
        errors = errors.withSource(implementation);
    } else {
        errors = errors.withSource(returnType).withSource(implementation);
    }
    Class<?> rawType = implementation.getRawType();
    if (Modifier.isInterface(rawType.getModifiers())) {
        errors.addMessage("%s is an interface, not a concrete class.  Unable to create AssistedInject factory.", implementation);
        throw errors.toException();
    } else if (Modifier.isAbstract(rawType.getModifiers())) {
        errors.addMessage("%s is abstract, not a concrete class.  Unable to create AssistedInject factory.", implementation);
        throw errors.toException();
    } else if (Classes.isInnerClass(rawType)) {
        errors.cannotInjectInnerClass(rawType);
        throw errors.toException();
    }
    Constructor<?> matchingConstructor = null;
    boolean anyAssistedInjectConstructors = false;
    // Look for AssistedInject constructors...
    for (Constructor<?> constructor : rawType.getDeclaredConstructors()) {
        if (constructor.isAnnotationPresent(AssistedInject.class)) {
            anyAssistedInjectConstructors = true;
            if (constructorHasMatchingParams(implementation, constructor, paramList, errors)) {
                if (matchingConstructor != null) {
                    errors.addMessage("%s has more than one constructor annotated with @AssistedInject" + " that matches the parameters in method %s.  Unable to create " + "AssistedInject factory.", implementation, method);
                    throw errors.toException();
                } else {
                    matchingConstructor = constructor;
                }
            }
        }
    }
    if (!anyAssistedInjectConstructors) {
        // If none existed, use @Inject or a no-arg constructor.
        try {
            return InjectionPoint.forConstructorOf(implementation);
        } catch (ConfigurationException e) {
            errors.merge(e.getErrorMessages());
            throw errors.toException();
        }
    } else {
        // Otherwise, use it or fail with a good error message.
        if (matchingConstructor != null) {
            // safe because we got the constructor from this implementation.
            @SuppressWarnings("unchecked") InjectionPoint ip = InjectionPoint.forConstructor((Constructor<? super T>) matchingConstructor, implementation);
            return ip;
        } else {
            errors.addMessage("%s has @AssistedInject constructors, but none of them match the" + " parameters in method %s.  Unable to create AssistedInject factory.", implementation, method);
            throw errors.toException();
        }
    }
}
Also used : Errors(com.google.inject.internal.Errors) ConfigurationException(com.google.inject.ConfigurationException) InjectionPoint(com.google.inject.spi.InjectionPoint)

Example 19 with ConfigurationException

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

the class FactoryProvider2 method initialize.

/**
 * At injector-creation time, we initialize the invocation handler. At this time we make sure all
 * factory methods will be able to build the target types.
 */
@Inject
@Toolable
void initialize(Injector injector) {
    if (this.injector != null) {
        throw new ConfigurationException(ImmutableList.of(new Message(FactoryProvider2.class, "Factories.create() factories may only be used in one Injector!")));
    }
    this.injector = injector;
    for (Map.Entry<Method, AssistData> entry : assistDataByMethod.entrySet()) {
        Method method = entry.getKey();
        AssistData data = entry.getValue();
        Object[] args;
        if (!data.optimized) {
            args = new Object[method.getParameterTypes().length];
            Arrays.fill(args, "dummy object for validating Factories");
        } else {
            // won't be used -- instead will bind to data.providers.
            args = null;
        }
        getBindingFromNewInjector(method, args, // throws if the binding isn't properly configured
        data);
    }
}
Also used : Message(com.google.inject.spi.Message) ConfigurationException(com.google.inject.ConfigurationException) Method(java.lang.reflect.Method) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Inject(com.google.inject.Inject) Toolable(com.google.inject.spi.Toolable)

Example 20 with ConfigurationException

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

the class DaggerAdapterTest method testFilteringMethods.

public void testFilteringMethods() {
    Module filteredModule = DaggerAdapter.builder().addModules(ImmutableList.of(ModuleWithMethodsToIgnore.class)).filter(new Predicate<Method>() {

        @Override
        public boolean apply(Method method) {
            return !method.getName().startsWith("ignore");
        }
    }).build();
    Injector filteredInjector = Guice.createInjector(filteredModule);
    assertThat(filteredInjector.getInstance(String.class)).isEqualTo("class");
    try {
        filteredInjector.getInstance(Integer.class);
        fail();
    } catch (ConfigurationException expected) {
    // 
    }
    try {
        filteredInjector.getInstance(ModuleWithMethodsToIgnore.Inerface.class);
        fail();
    } catch (ConfigurationException expected) {
    // 
    }
    Module unfilteredModule = DaggerAdapter.builder().addModules(ImmutableList.of(ModuleWithMethodsToIgnore.class)).build();
    Injector unfilteredInjector = Guice.createInjector(unfilteredModule);
    assertThat(unfilteredInjector.getInstance(String.class)).isEqualTo("class");
    assertThat(unfilteredInjector.getInstance(Integer.class)).isEqualTo(Integer.valueOf(0));
    assertThat(unfilteredInjector.getInstance(ModuleWithMethodsToIgnore.Inerface.class).string()).isEqualTo("class");
}
Also used : ConfigurationException(com.google.inject.ConfigurationException) Injector(com.google.inject.Injector) Method(java.lang.reflect.Method) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) Predicate(com.google.common.base.Predicate)

Aggregations

ConfigurationException (com.google.inject.ConfigurationException)62 Injector (com.google.inject.Injector)16 Errors (com.google.inject.internal.Errors)13 InjectionPoint (com.google.inject.spi.InjectionPoint)8 Method (java.lang.reflect.Method)7 AbstractModule (com.google.inject.AbstractModule)5 Inject (com.google.inject.Inject)5 ErrorsException (com.google.inject.internal.ErrorsException)5 Annotation (java.lang.annotation.Annotation)5 TypeLiteral (com.google.inject.TypeLiteral)4 Map (java.util.Map)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 GuiceUtil (com.google.gwt.inject.rebind.util.GuiceUtil)3 Module (com.google.inject.Module)3 Message (com.google.inject.spi.Message)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Binding (com.google.inject.Binding)2