Search in sources :

Example 81 with Provides

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

the class Struts2FactoryTest method testStruts2Factory.

public void testStruts2Factory() {
    Struts2Factory s2Factory = new Struts2Factory();
    TestListener testListener = new TestListener(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        @SuppressWarnings("unused")
        Date provideDate() {
            return TODAY;
        }
    });
    assertEquals(TODAY, testListener.getInjector().getInstance(Date.class));
    assertEquals(TODAY, s2Factory.buildBean(Date.class, null));
}
Also used : Provides(com.google.inject.Provides) Date(java.util.Date) AbstractModule(com.google.inject.AbstractModule)

Example 82 with Provides

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

the class ProviderMethodsModule method getProviderMethods.

public List<ProviderMethod<?>> getProviderMethods(Binder binder) {
    List<ProviderMethod<?>> result = null;
    // The highest class in the type hierarchy that contained a provider method definition.
    Class<?> superMostClass = delegate.getClass();
    for (Class<?> c = delegate.getClass(); c != Object.class; c = c.getSuperclass()) {
        for (Method method : c.getDeclaredMethods()) {
            Annotation annotation = getAnnotation(binder, method);
            if (annotation != null) {
                if (result == null) {
                    result = Lists.newArrayList();
                }
                result.add(createProviderMethod(binder, method, annotation));
                superMostClass = c;
            }
        }
    }
    if (result == null) {
        // We didn't find anything
        return ImmutableList.of();
    }
    // We have found some provider methods, now we need to check if any were overridden.
    // We do this as a separate pass to avoid calculating all the signatures when there are no
    // provides methods, or when all provides methods are defined in a single class.
    Multimap<Signature, Method> methodsBySignature = null;
    // no overrides of a provides method.
    for (Class<?> c = delegate.getClass(); c != superMostClass; c = c.getSuperclass()) {
        for (Method method : c.getDeclaredMethods()) {
            if (((method.getModifiers() & (Modifier.PRIVATE | Modifier.STATIC)) == 0) && !method.isBridge() && !method.isSynthetic()) {
                if (methodsBySignature == null) {
                    methodsBySignature = HashMultimap.create();
                }
                methodsBySignature.put(new Signature(typeLiteral, method), method);
            }
        }
    }
    if (methodsBySignature != null) {
        // only assuming that every method is an override, in general it should be very quick.
        for (ProviderMethod<?> provider : result) {
            Method method = provider.getMethod();
            for (Method matchingSignature : methodsBySignature.get(new Signature(typeLiteral, method))) {
                // overridding it.
                if (matchingSignature.getDeclaringClass().isAssignableFrom(method.getDeclaringClass())) {
                    continue;
                }
                // now we know matching signature is in a subtype of method.getDeclaringClass()
                if (overrides(matchingSignature, method)) {
                    String annotationString = provider.getAnnotation().annotationType() == Provides.class ? "@Provides" : "@" + provider.getAnnotation().annotationType().getCanonicalName();
                    binder.addError("Overriding " + annotationString + " methods is not allowed." + "\n\t" + annotationString + " method: %s\n\toverridden by: %s", method, matchingSignature);
                    break;
                }
            }
        }
    }
    return result;
}
Also used : Method(java.lang.reflect.Method) Provides(com.google.inject.Provides) Annotation(java.lang.annotation.Annotation)

Example 83 with Provides

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

the class ProvidesMethodScanner method prepareMethod.

// mapKey doesn't know its key type
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <T> Key<T> prepareMethod(Binder binder, Annotation annotation, Key<T> key, InjectionPoint injectionPoint) {
    Method method = (Method) injectionPoint.getMember();
    AnnotationOrError mapKey = findMapKeyAnnotation(binder, method);
    if (annotation instanceof Provides) {
        if (mapKey.annotation != null) {
            binder.addError("Found a MapKey annotation on non map binding at %s.", method);
        }
        // no key rewriting for plain old @Provides
        return key;
    }
    if (annotation instanceof ProvidesIntoSet) {
        if (mapKey.annotation != null) {
            binder.addError("Found a MapKey annotation on non map binding at %s.", method);
        }
        return RealMultibinder.newRealSetBinder(binder, key).getKeyForNewItem();
    } else if (annotation instanceof ProvidesIntoMap) {
        if (mapKey.error) {
            // Already failed on the MapKey, don't bother doing more work.
            return key;
        }
        if (mapKey.annotation == null) {
            // If no MapKey, make an error and abort.
            binder.addError("No MapKey found for map binding at %s.", method);
            return key;
        }
        TypeAndValue typeAndValue = typeAndValueOfMapKey(mapKey.annotation);
        return RealMapBinder.newRealMapBinder(binder, typeAndValue.type, key).getKeyForNewValue(typeAndValue.value);
    } else if (annotation instanceof ProvidesIntoOptional) {
        if (mapKey.annotation != null) {
            binder.addError("Found a MapKey annotation on non map binding at %s.", method);
        }
        switch(((ProvidesIntoOptional) annotation).value()) {
            case DEFAULT:
                return RealOptionalBinder.newRealOptionalBinder(binder, key).getKeyForDefaultBinding();
            case ACTUAL:
                return RealOptionalBinder.newRealOptionalBinder(binder, key).getKeyForActualBinding();
        }
    }
    throw new IllegalStateException("Invalid annotation: " + annotation);
}
Also used : ProvidesIntoMap(com.google.inject.multibindings.ProvidesIntoMap) ProvidesIntoOptional(com.google.inject.multibindings.ProvidesIntoOptional) Method(java.lang.reflect.Method) Provides(com.google.inject.Provides) ProvidesIntoSet(com.google.inject.multibindings.ProvidesIntoSet)

Example 84 with Provides

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

the class ProviderMethodsTest method testScopedProviderMethodThrowsException.

public void testScopedProviderMethodThrowsException() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        @Singleton
        int provideInt() {
            throw new RuntimeException("boom");
        }
    });
    Provider<Integer> intProvider = injector.getProvider(Integer.class);
    try {
        intProvider.get();
        fail();
    } catch (ProvisionException pe) {
        // by default assertContains asserts that the last item doesn't repeat... which is the main
        // thing we are testing for
        assertContains(pe.getMessage(), "java.lang.RuntimeException: boom", "provideInt");
    }
}
Also used : ProvisionException(com.google.inject.ProvisionException) Injector(com.google.inject.Injector) Singleton(com.google.inject.Singleton) Provides(com.google.inject.Provides) AbstractModule(com.google.inject.AbstractModule)

Example 85 with Provides

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

the class ProviderMethodsTest method testCircularDependency.

public void testCircularDependency() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        Foo newFoo(final Bar bar) {
            return new Foo() {

                @Override
                public Bar getBar() {
                    return bar;
                }

                @Override
                public int getI() {
                    return 5;
                }
            };
        }

        @Provides
        Bar newBar(final Foo foo) {
            return new Bar() {

                @Override
                public Foo getFoo() {
                    return foo;
                }

                @Override
                public int getI() {
                    return 10;
                }
            };
        }
    });
    Foo foo = injector.getInstance(Foo.class);
    assertEquals(5, foo.getI());
    assertEquals(10, foo.getBar().getI());
    assertEquals(5, foo.getBar().getFoo().getI());
}
Also used : Injector(com.google.inject.Injector) Provides(com.google.inject.Provides) AbstractModule(com.google.inject.AbstractModule)

Aggregations

Provides (com.google.inject.Provides)126 Singleton (javax.inject.Singleton)36 AbstractModule (com.google.inject.AbstractModule)26 Singleton (com.google.inject.Singleton)24 Injector (com.google.inject.Injector)22 Named (javax.inject.Named)17 LazySingleton (io.druid.guice.LazySingleton)12 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 Named (com.google.inject.name.Named)8 IOException (java.io.IOException)7 File (java.io.File)6 ArrayList (java.util.ArrayList)6 Inject (javax.inject.Inject)6 Properties (java.util.Properties)5 Client (javax.ws.rs.client.Client)5 Test (org.junit.Test)5 Key (com.google.inject.Key)4 ExecutorService (java.util.concurrent.ExecutorService)4 ConfigModule (co.cask.cdap.common.guice.ConfigModule)3 Binder (com.google.inject.Binder)3