Java 类com.google.inject.Binding 实例源码

项目:ProjectAres    文件:Scoper.java   
@Override
public Void visit(ExposedBinding<? extends T> binding) {
    final PrivateBinder privateBinder = this.binder.newPrivateBinder();
    final Scoper scoper = new Scoper(privateBinder, scoping);
    for(Element element : binding.getPrivateElements().getElements()) {
        if(element instanceof Binding) {
            ((Binding) element).acceptTargetVisitor(scoper);
        } else {
            element.applyTo(privateBinder);
        }
    }
    for(Key key : binding.getPrivateElements().getExposedKeys()) {
        privateBinder.expose(key);
    }
    return null;
}
项目:Equella    文件:GuicePlugin.java   
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(String beanId)
{
    Injector injector = ensureInjector();
    Key<Object> nameKey = Key.get(Object.class, Names.named(beanId));
    Binding<Object> binding = injector.getExistingBinding(nameKey);
    if( binding != null )
    {
        return (T) binding.getProvider().get();
    }
    ClassLoader classLoader = privatePluginService.getClassLoader(pluginId);
    try
    {
        Class<?> clazz = classLoader.loadClass(beanId);
        return (T) injector.getInstance(clazz);
    }
    catch( ClassNotFoundException e )
    {
        throw new RuntimeException(e);
    }
}
项目:abhot    文件:GuiceQueryPluginFactory.java   
@Inject
@SuppressWarnings("unchecked")
public GuiceQueryPluginFactory(Injector injector)
{
    m_injector = injector;
    Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

    for (Key<?> key : bindings.keySet())
    {
        Class<?> bindingClass = key.getTypeLiteral().getRawType();
        if (QueryPlugin.class.isAssignableFrom(bindingClass))
        {
            PluginName ann = (PluginName) bindingClass.getAnnotation(PluginName.class);
            if (ann == null)
                throw new IllegalStateException("Aggregator class " + bindingClass.getName() +
                        " does not have required annotation " + PluginName.class.getName());

            m_plugins.put(ann.name(), (Class<QueryPlugin>)bindingClass);
        }
    }
}
项目:abhot    文件:Main.java   
public void startServices() throws KairosDBException
{
    Map<Key<?>, Binding<?>> bindings =
            m_injector.getAllBindings();

    for (Key<?> key : bindings.keySet())
    {
        Class<?> bindingClass = key.getTypeLiteral().getRawType();
        if (KairosDBService.class.isAssignableFrom(bindingClass))
        {
            KairosDBService service = (KairosDBService) m_injector.getInstance(bindingClass);
            logger.info("Starting service " + bindingClass);
            service.start();
            m_services.add(service);
        }
    }
}
项目:abhot    文件:GuiceGroupByFactory.java   
@Inject
@SuppressWarnings("unchecked")
public GuiceGroupByFactory(Injector injector)
{
    this.injector = injector;
    Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

    for (Key<?> key : bindings.keySet())
    {
        Class<?> bindingClass = key.getTypeLiteral().getRawType();
        if (GroupBy.class.isAssignableFrom(bindingClass))
        {
            GroupByName name = (GroupByName)bindingClass.getAnnotation(GroupByName.class);
            if (name == null)
                throw new IllegalStateException("Aggregator class "+bindingClass.getName()+
                        " does not have required annotation "+GroupByName.class.getName());

            groupBys.put(name.name(), (Class<GroupBy>)bindingClass);
        }
    }
}
项目:abhot    文件:HealthCheckServiceImpl.java   
@Inject
public HealthCheckServiceImpl(Injector injector)
{
    checkNotNull(injector);

    Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

    for (Key<?> key : bindings.keySet())
    {
        Class<?> bindingClass = key.getTypeLiteral().getRawType();
        if (HealthStatus.class.isAssignableFrom(bindingClass))
        {
            checks.add((HealthStatus) injector.getInstance(bindingClass));
        }
    }
}
项目:bootique-tapestry    文件:GuiceObjectProvider.java   
@Override
public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider, ObjectLocator locator) {

    TypeLiteral<T> type = TypeLiteral.get(objectType);
    List<Binding<T>> bindings = injector.findBindingsByType(type);

    for (Binding<T> binding : bindings) {

        Class<? extends Annotation> annotationType = binding.getKey().getAnnotationType();
        Annotation annotation = annotationType != null ? annotationProvider.getAnnotation(annotationType) : null;

        Key<T> key = annotation != null ? Key.get(type, annotation) : Key.get(type);
        if (key.equals(binding.getKey())) {
            return injector.getInstance(key);
        }
    }

    return null;
}
项目:endpoints-java    文件:EndpointsModuleTest.java   
@Test
public void testConfigureEndpoints_withInterceptor() {
  Injector injector = Guice.createInjector(module, new InterceptorModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern());
  assertEquals("Wrong initialization parameter provided", "false",
      servletBinding.getInitParams().get("restricted"));
  assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider);

  ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get();
  Collection<Object> services = serviceMap.getServices();
  assertEquals("Incorrect number of services provided", 1, services.size());
  assertEquals("Service not enhanced correctly.", SERVICES.toArray()[0],
      ((Class<?>) services.toArray()[0].getClass()).getSuperclass());
}
项目:endpoints-java    文件:EndpointsModuleTest.java   
@Test
public void testConfigureEndpoints_withoutInterceptor() {
  Injector injector = Guice.createInjector(module, new DummyModule());

  Visitor visitor = new Visitor();
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }

  assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size());
  LinkedServletBinding servletBinding = visitor.linkedServlets.get(0);
  assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern());
  assertEquals("Wrong initialization parameter provided", "false",
      servletBinding.getInitParams().get("restricted"));
  assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider);

  ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get();
  Collection<Object> services = serviceMap.getServices();
  assertEquals("Incorrect number of services provided", 1, services.size());
  assertEquals("Service not provided correctly.", SERVICES.toArray()[0],
      services.toArray()[0].getClass());
}
项目:bootique-linkrest    文件:LinkRestModule.java   
@Singleton
@Provides
LinkRestRuntime provideLinkRestRuntime(
        Injector injector,
        Set<LrFeatureProvider> featureProviders,
        Set<LinkRestAdapter> adapters) {

    LinkRestBuilder builder;

    Binding<ServerRuntime> binding = injector.getExistingBinding(Key.get(ServerRuntime.class));
    if (binding == null) {
        builder = new LinkRestBuilder().cayenneService(new PojoCayennePersister());
    } else {
        ServerRuntime cayenneRuntime = binding.getProvider().get();
        builder = new LinkRestBuilder().cayenneRuntime(cayenneRuntime);
    }

    featureProviders.forEach(builder::feature);
    adapters.forEach(builder::adapter);

    return builder.build();
}
项目:guice-scoped-proxy-extension    文件:ScopedProxyBinder.java   
@Inject
@Toolable
@SuppressWarnings("unchecked")
void initialize(Injector injector) {
    final Binding<T> realBinding = injector.getBinding(this.rewritten);
    final Provider<T> realProvider = injector.getProvider(realBinding.getKey());

    // The proxy will be a sub type of the source type of the binding
    final Class<T> proxyType = (Class<T>) realBinding.getKey()
            .getTypeLiteral().getRawType();

    this.dependencies = Collections.singleton(
            Dependency.get(this.rewritten));
    this.ref = InstanceBuilder.forType(proxyType)
            .withConstructionStrategy(this.strategy)
            .dispatchTo(realProvider)
            .create(injector);
}
项目:Camel    文件:NamedProviderSupport.java   
protected Object provideObjectFromNamedBindingOrJndi(
        TypeLiteral<?> requiredType, String name) {
    Binding<?> binding = Injectors.getBinding(injector,
            Key.get(requiredType, Names.named(name)));
    if (binding != null) {
        return binding.getProvider().get();
    }

    // TODO we may want to try avoid the dependency on JNDI classes
    // for better operation in GAE?
    try {
        if (context == null) {
            context = new InitialContext();
        }
        return context.lookup(name);
    } catch (NamingException e) {
        throw new ProvisionException("Failed to find name '" + name
                + "' in JNDI. Cause: " + e, e);
    }
}
项目:Camel    文件:Main.java   
protected Map<String, CamelContext> getCamelContextMap() {
    Map<String, CamelContext> answer = Maps.newHashMap();
    if (injector != null) {
        Set<Map.Entry<Key<?>, Binding<?>>> entries = injector.getBindings().entrySet();
        for (Map.Entry<Key<?>, Binding<?>> entry : entries) {
            Key<?> key = entry.getKey();
            Class<?> keyType = Injectors.getKeyType(key);
            if (keyType != null && CamelContext.class.isAssignableFrom(keyType)) {
                Binding<?> binding = entry.getValue();
                Object value = binding.getProvider().get();
                if (value != null) {
                    CamelContext castValue = CamelContext.class.cast(value);
                    answer.put(key.toString(), castValue);
                }
            }
        }
    }
    return answer;
}
项目:Camel    文件:Injectors.java   
/**
 * Returns a collection of all instances of the given base type
 * 
 * @param baseClass
 *            the base type of objects required
 * @param <T>
 *            the base type
 * @return a set of objects returned from this injector
 */
public static <T> Set<T> getInstancesOf(Injector injector,
        Class<T> baseClass) {
    Set<T> answer = Sets.newHashSet();
    Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings()
            .entrySet();
    for (Entry<Key<?>, Binding<?>> entry : entries) {
        Key<?> key = entry.getKey();
        Class<?> keyType = getKeyType(key);
        if (keyType != null && baseClass.isAssignableFrom(keyType)) {
            Binding<?> binding = entry.getValue();
            Object value = binding.getProvider().get();
            if (value != null) {
                T castValue = baseClass.cast(value);
                answer.add(castValue);
            }
        }
    }
    return answer;
}
项目:Camel    文件:Injectors.java   
/**
 * Returns a collection of all instances matching the given matcher
 * 
 * @param matcher
 *            matches the types to return instances
 * @return a set of objects returned from this injector
 */
public static <T> Set<T> getInstancesOf(Injector injector,
        Matcher<Class> matcher) {
    Set<T> answer = Sets.newHashSet();
    Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings()
            .entrySet();
    for (Entry<Key<?>, Binding<?>> entry : entries) {
        Key<?> key = entry.getKey();
        Class<?> keyType = getKeyType(key);
        if (keyType != null && matcher.matches(keyType)) {
            Binding<?> binding = entry.getValue();
            Object value = binding.getProvider().get();
            answer.add((T) value);
        }
    }
    return answer;
}
项目:Camel    文件:Injectors.java   
/**
 * Returns a collection of all of the providers matching the given matcher
 * 
 * @param matcher
 *            matches the types to return instances
 * @return a set of objects returned from this injector
 */
public static <T> Set<Provider<T>> getProvidersOf(Injector injector,
        Matcher<Class> matcher) {
    Set<Provider<T>> answer = Sets.newHashSet();
    Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings()
            .entrySet();
    for (Entry<Key<?>, Binding<?>> entry : entries) {
        Key<?> key = entry.getKey();
        Class<?> keyType = getKeyType(key);
        if (keyType != null && matcher.matches(keyType)) {
            Binding<?> binding = entry.getValue();
            answer.add((Provider<T>) binding.getProvider());
        }
    }
    return answer;
}
项目:Camel    文件:Injectors.java   
/**
 * Returns a collection of all providers of the given base type
 * 
 * @param baseClass
 *            the base type of objects required
 * @param <T>
 *            the base type
 * @return a set of objects returned from this injector
 */
public static <T> Set<Provider<T>> getProvidersOf(Injector injector,
        Class<T> baseClass) {
    Set<Provider<T>> answer = Sets.newHashSet();
    Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings()
            .entrySet();
    for (Entry<Key<?>, Binding<?>> entry : entries) {
        Key<?> key = entry.getKey();
        Class<?> keyType = getKeyType(key);
        if (keyType != null && baseClass.isAssignableFrom(keyType)) {
            Binding<?> binding = entry.getValue();
            answer.add((Provider<T>) binding.getProvider());
        }
    }
    return answer;
}
项目:Camel    文件:Injectors.java   
/**
 * Closes objects within the given scope using the currently registered
 * {@link Closer} implementations
 */
public static void close(Injector injector,
        Class<? extends Annotation> scopeAnnotationToClose,
        CloseErrors errors) throws CloseFailedException {
    Set<Closer> closers = getInstancesOf(injector, Closer.class);
    Closer closer = CompositeCloser.newInstance(closers);
    if (closer == null) {
        return;
    }

    Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings()
            .entrySet();
    for (Entry<Key<?>, Binding<?>> entry : entries) {
        Key<?> key = entry.getKey();
        Binding<?> binding = entry.getValue();
        closeBinding(key, binding, scopeAnnotationToClose, closer, errors);
    }

    tryCloseJitBindings(closer, injector, scopeAnnotationToClose, errors);
    errors.throwIfNecessary();
}
项目:salta    文件:Jsr330Test.java   
@Override
public <T> com.google.inject.Provider<T> scope(
        com.github.ruediste.salta.core.Binding binding,
        CoreDependencyKey<T> requestedKey,
        com.google.inject.Provider<T> unscoped) {
    return new com.google.inject.Provider<T>() {
        private T value;
        private int snapshotTime = -1;

        @Override
        public T get() {
            if (snapshotTime != now) {
                value = unscoped.get();
                snapshotTime = now;
            }
            return value;
        }
    };
}
项目:microservice-bundle    文件:GuiceRegistry.java   
@Override
public Object lookupByName(String name) {
  Object answer = null;

  Map<Key<?>, Binding<?>> bindings = injector.getBindings();

  for (Key<?> key : bindings.keySet()) {
    Annotation annotation = key.getAnnotation();
    if (annotation instanceof CamelBind) {
      if (((CamelBind) annotation).value().equals(name)) {
        answer = injector.getInstance(key);
      }
    }
  }
  if (answer == null) {
    try {
      Class clazz = Class.forName(name);
      answer = injector.getInstance(clazz);
    } catch (ClassNotFoundException e) {
      String msg = "Bean with " + name + " not found in Guice registry ...";
      logger.info(msg);
    }
  }
  return answer;
}
项目:microservice-bundle    文件:GuiceRegistry.java   
@Override
public <T> Map<String, T> findByTypeWithName(Class<T> type) {
  Map<String, T> result = Maps.newHashMap();

  Map<Key<?>, Binding<?>> bindings = injector.getBindings();

  for (Key<?> key : bindings.keySet()) {
    if (key.getTypeLiteral().getRawType().isAssignableFrom(type)) {
      Annotation annotation = key.getAnnotation();
      String name = null;
      Object inst = injector.getInstance(key);
      if (annotation != null && annotation instanceof CamelBind) {
        name = ((CamelBind) key.getAnnotation()).value();

      } else {
        name = type.getName();
      }
      logger.debug("Found binding for name: {} with value: {}", name, inst);
      result.put(name, type.cast(inst));
    }
  }
  return result;
}
项目:guiceberry    文件:ModuleWriter.java   
protected void applyScoping(Binding<?> binding, final ScopedBindingBuilder scopedBindingBuilder) {
  binding.acceptScopingVisitor(new BindingScopingVisitor<Void>() {
    public Void visitEagerSingleton() {
      if (scopedBindingBuilder != null) {
        scopedBindingBuilder.asEagerSingleton();
      }
      return null;
    }

    public Void visitScope(Scope scope) {
      scopedBindingBuilder.in(scope);
      return null;
    }

    public Void visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
      scopedBindingBuilder.in(scopeAnnotation);
      return null;
    }

    public Void visitNoScoping() {
      // do nothing
      return null;
    }
  });
}
项目:guiceberry    文件:ModuleWriter.java   
protected void applyScoping(Binding<?> binding, final ScopedBindingBuilder scopedBindingBuilder) {
  binding.acceptScopingVisitor(new BindingScopingVisitor<Void>() {
    public Void visitEagerSingleton() {
      if (scopedBindingBuilder != null) {
        scopedBindingBuilder.asEagerSingleton();
      }
      return null;
    }

    public Void visitScope(Scope scope) {
      scopedBindingBuilder.in(scope);
      return null;
    }

    public Void visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
      scopedBindingBuilder.in(scopeAnnotation);
      return null;
    }

    public Void visitNoScoping() {
      // do nothing
      return null;
    }
  });
}
项目:bootique-linkrest    文件:LinkRestModule.java   
@Singleton
@Provides
LinkRestRuntime provideLinkRestRuntime(
        Injector injector,
        Set<LrFeatureProvider> featureProviders,
        Set<LinkRestAdapter> adapters) {

    LinkRestBuilder builder;

    Binding<ServerRuntime> binding = injector.getExistingBinding(Key.get(ServerRuntime.class));
    if (binding == null) {
        builder = new LinkRestBuilder().cayenneService(new PojoCayennePersister());
    } else {
        ServerRuntime cayenneRuntime = binding.getProvider().get();
        builder = new LinkRestBuilder().cayenneRuntime(cayenneRuntime);
    }

    featureProviders.forEach(builder::feature);
    adapters.forEach(builder::adapter);

    return builder.build();
}
项目:gerrit    文件:DispatchCommandProvider.java   
@SuppressWarnings("unchecked")
private ConcurrentMap<String, CommandProvider> createMap() {
  ConcurrentMap<String, CommandProvider> m = Maps.newConcurrentMap();
  for (Binding<?> b : allCommands()) {
    final Annotation annotation = b.getKey().getAnnotation();
    if (annotation instanceof CommandName) {
      final CommandName n = (CommandName) annotation;
      if (!Commands.CMD_ROOT.equals(n) && Commands.isChild(parent, n)) {
        String descr = null;
        if (annotation instanceof Commands.NestedCommandNameImpl) {
          Commands.NestedCommandNameImpl impl = ((Commands.NestedCommandNameImpl) annotation);
          descr = impl.descr();
        }
        m.put(n.value(), new CommandProvider((Provider<Command>) b.getProvider(), descr));
      }
    }
  }
  return m;
}
项目:gerrit    文件:PrivateInternals_DynamicTypes.java   
public static Map<TypeLiteral<?>, DynamicItem<?>> dynamicItemsOf(Injector src) {
  Map<TypeLiteral<?>, DynamicItem<?>> m = new HashMap<>();
  for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
    TypeLiteral<?> type = e.getKey().getTypeLiteral();
    if (type.getRawType() == DynamicItem.class) {
      ParameterizedType p = (ParameterizedType) type.getType();
      m.put(
          TypeLiteral.get(p.getActualTypeArguments()[0]),
          (DynamicItem<?>) e.getValue().getProvider().get());
    }
  }
  if (m.isEmpty()) {
    return Collections.emptyMap();
  }
  return Collections.unmodifiableMap(m);
}
项目:gerrit    文件:PrivateInternals_DynamicTypes.java   
public static Map<TypeLiteral<?>, DynamicSet<?>> dynamicSetsOf(Injector src) {
  Map<TypeLiteral<?>, DynamicSet<?>> m = new HashMap<>();
  for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
    TypeLiteral<?> type = e.getKey().getTypeLiteral();
    if (type.getRawType() == DynamicSet.class) {
      ParameterizedType p = (ParameterizedType) type.getType();
      m.put(
          TypeLiteral.get(p.getActualTypeArguments()[0]),
          (DynamicSet<?>) e.getValue().getProvider().get());
    }
  }
  if (m.isEmpty()) {
    return Collections.emptyMap();
  }
  return Collections.unmodifiableMap(m);
}
项目:gerrit    文件:PrivateInternals_DynamicTypes.java   
public static Map<TypeLiteral<?>, DynamicMap<?>> dynamicMapsOf(Injector src) {
  Map<TypeLiteral<?>, DynamicMap<?>> m = new HashMap<>();
  for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
    TypeLiteral<?> type = e.getKey().getTypeLiteral();
    if (type.getRawType() == DynamicMap.class) {
      ParameterizedType p = (ParameterizedType) type.getType();
      m.put(
          TypeLiteral.get(p.getActualTypeArguments()[0]),
          (DynamicMap<?>) e.getValue().getProvider().get());
    }
  }
  if (m.isEmpty()) {
    return Collections.emptyMap();
  }
  return Collections.unmodifiableMap(m);
}
项目:guice-scoped-proxy-extension    文件:ScopedProxyBinder.java   
@Inject
@Toolable
@SuppressWarnings("unchecked")
void initialize(Injector injector) {
    final Binding<T> realBinding = injector.getBinding(this.rewritten);
    final Provider<T> realProvider = injector.getProvider(realBinding.getKey());

    // The proxy will be a sub type of the source type of the binding
    final Class<T> proxyType = (Class<T>) realBinding.getKey()
            .getTypeLiteral().getRawType();

    this.dependencies = Collections.singleton(
            Dependency.get(this.rewritten));
    this.ref = InstanceBuilder.forType(proxyType)
            .withConstructionStrategy(this.strategy)
            .dispatchTo(realProvider)
            .create(injector);
}
项目:guice    文件:SpiBindingsTest.java   
public void checkInjector(Module module, ElementVisitor<?>... visitors) {
  Injector injector = Guice.createInjector(module);

  List<Binding<?>> bindings = Lists.newArrayList(injector.getBindings().values());
  for (Iterator<Binding<?>> i = bindings.iterator(); i.hasNext(); ) {
    if (BUILT_IN_BINDINGS.contains(i.next().getKey())) {
      i.remove();
    }
  }

  Collections.sort(bindings, orderByKey);

  assertEquals(bindings.size(), visitors.length);

  for (int i = 0; i < visitors.length; i++) {
    ElementVisitor<?> visitor = visitors[i];
    Binding<?> binding = bindings.get(i);
    binding.acceptVisitor(visitor);
  }
}
项目:fabricator    文件:NamedComponentManagerBinding.java   
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
    TypeLiteral<ComponentManager<?>> managerLiteral = (TypeLiteral<ComponentManager<?>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, argType));
    Binding<ComponentManager<?>> managerBinding = injector.getExistingBinding(Key.get(managerLiteral));
    if (managerBinding != null) {
        ComponentManager<?> manager = managerBinding.getProvider().get();
        try {
            method.invoke(obj, manager.get(name));
            return true;
        }
        catch (Exception e) {
            throw new Exception(String.format(
                    "Unable to get component '%s' (%s) for property '%s' must be one of %s",
                    name, argType.getSimpleName(), propertyName, manager.getIds()), e);
        }
    }
    return false;    
}
项目:fabricator    文件:NamedBinding.java   
@Override
public boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception {

    Binding<?> binding;

    Type pType = method.getGenericParameterTypes()[0];
    if (pType != null) {
        binding = injector.getExistingBinding(Key.get(pType, Names.named(name)));
    }
    else {
        binding = injector.getExistingBinding(Key.get(argType, Names.named(name)));
    }

    if (binding != null) {
        method.invoke(obj, binding.getProvider().get());
        return true;
    }
    return false;
}
项目:guice    文件:RealMapBinder.java   
@Override
protected void doInitialize(InjectorImpl injector, Errors errors) {
  ImmutableMap.Builder<K, Set<Provider<V>>> multimapOfProvidersBuilder =
      ImmutableMap.builder();
  ImmutableSet.Builder<Dependency<?>> dependenciesBuilder = ImmutableSet.builder();
  for (Map.Entry<K, Set<Binding<V>>> entry :
      bindingSelection.getMultimapBindings().entrySet()) {
    ImmutableSet.Builder<Provider<V>> providersBuilder = ImmutableSet.builder();
    for (Binding<V> binding : entry.getValue()) {
      providersBuilder.add(binding.getProvider());
      dependenciesBuilder.add(Dependency.get(getKeyOfProvider(binding.getKey())));
    }

    multimapOfProvidersBuilder.put(entry.getKey(), providersBuilder.build());
  }
  multimapOfProviders = multimapOfProvidersBuilder.build();
  dependencies = dependenciesBuilder.build();
}
项目:guice-old    文件:ElementsTest.java   
public void testBindToInstanceScope() {
  checkModule(
      new AbstractModule() {
        protected void configure() {
          bind(String.class).toInstance("A");
        }
      },

      new FailingElementVisitor() {
        @Override public <T> Void visit(Binding<T> binding) {
          assertEquals(Key.get(String.class), binding.getKey());
          binding.acceptScopingVisitor(new FailingBindingScopingVisitor() {
            public Void visitEagerSingleton() {
              return null;
            }
          });
          return null;
        }
      }
    );
}
项目:deguicifier    文件:Generators.java   
private static String instantiation(Binding<?> binding) {
  if (binding instanceof InstanceBinding<?>) {
    return instanceLiteral((InstanceBinding<?>) binding);
  } else if (binding instanceof ProviderKeyBinding<?>) {
    return providerCall(((ProviderKeyBinding<?>) binding).getProviderKey()) + ".get()";
  } else if (binding instanceof LinkedKeyBinding<?>) {
    return providerCall(((LinkedKeyBinding<?>) binding).getLinkedKey());
  } else if (binding instanceof ConstructorBinding<?>) {
    return constructorCall((ConstructorBinding<?>) binding);
  } else if (binding instanceof ProviderBinding<?>) {
    return provider((ProviderBinding<?>) binding);
  } else if (binding instanceof ProviderInstanceBinding<?>) {
    return instantiation((ProviderInstanceBinding<?>) binding);
  } else {
    throw new DeguicifierException();
  }
}
项目:guice    文件:ElementsTest.java   
public void testBindKeysWithAnnotationType() {
  FailingElementVisitor annotationChecker =
      new FailingElementVisitor() {
        @Override
        public <T> Void visit(Binding<T> command) {
          assertEquals(Key.get(String.class, SampleAnnotation.class), command.getKey());
          return null;
        }
      };

  checkModule(
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(String.class).annotatedWith(SampleAnnotation.class).toInstance("A");
          bind(new TypeLiteral<String>() {})
              .annotatedWith(SampleAnnotation.class)
              .toInstance("B");
        }
      },
      annotationChecker,
      annotationChecker);
}
项目:guice-old    文件:ServletModuleTest.java   
public void testServletModuleReuse() {
  Module module = new Module();
  Elements.getElements(module); // use the module once (to, say, introspect bindings)
  Injector injector = Guice.createInjector(module);  // use it again.

  Visitor visitor = new Visitor();    
  // Validate only a single servlet binding & a single filter binding exist.
  for(Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }
  assertEquals("wrong linked servlets: " + visitor.linkedServlets,
      0, visitor.linkedServlets.size());
  assertEquals("wrong linked filters: " + visitor.linkedFilters,
      0, visitor.linkedFilters.size());
  assertEquals("wrong instance servlets: " + visitor.instanceServlets,
      1, visitor.instanceServlets.size());
  assertEquals("wrong instance filters: " + visitor.instanceFilters,
      1, visitor.instanceFilters.size());
}
项目:guice-old    文件:MapBinder.java   
boolean containsElement(com.google.inject.spi.Element element) {
  if (entrySetBinder.containsElement(element)) {
    return true;
  } else {
    Key<?> key;
    if (element instanceof Binding) {
      key = ((Binding<?>)element).getKey();
    } else if (element instanceof ProviderLookup) {
      key = ((ProviderLookup<?>)element).getKey();
    } else {
      return false; // cannot match;
    }

    return key.equals(mapKey)
        || key.equals(providerMapKey)
        || key.equals(javaxProviderMapKey)
        || key.equals(multimapKey)
        || key.equals(providerMultimapKey)
        || key.equals(entrySetBinder.getSetKey())
        || matchesValueKey(key);
    }
}
项目:shiro-guice-resteasy-webapp    文件:GuiceRestEasyFilterDispatcher.java   
@Override
public void init(FilterConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    Registry registry = getDispatcher().getRegistry();
    ResteasyProviderFactory providerFactory = getDispatcher().getProviderFactory();

    for (final Binding<?> binding : injector.getBindings().values()) {
        Type type = binding.getKey().getTypeLiteral().getType();
        if (type instanceof Class) {
            Class<?> beanClass = (Class<?>) type;
            if (GetRestful.isRootResource(beanClass)) {
                ResourceFactory resourceFactory = new GuiceResourceFactory(binding.getProvider(), beanClass);
                log.info("registering factory for {}", beanClass.getName());
                registry.addResourceFactory(resourceFactory);
            }

            if (beanClass.isAnnotationPresent(Provider.class)) {
                log.info("registering provider instance for {}", beanClass.getName());
                providerFactory.registerProviderInstance(binding.getProvider().get());
            }
        }
    }
}
项目:guice    文件:ServletModuleTest.java   
public void testServletModuleReuse() {
  Module module = new Module();
  Elements.getElements(module); // use the module once (to, say, introspect bindings)
  Injector injector = Guice.createInjector(module); // use it again.

  Visitor visitor = new Visitor();
  // Validate only a single servlet binding & a single filter binding exist.
  for (Binding<?> binding : injector.getAllBindings().values()) {
    binding.acceptTargetVisitor(visitor);
  }
  assertEquals(
      "wrong linked servlets: " + visitor.linkedServlets, 0, visitor.linkedServlets.size());
  assertEquals("wrong linked filters: " + visitor.linkedFilters, 0, visitor.linkedFilters.size());
  assertEquals(
      "wrong instance servlets: " + visitor.instanceServlets, 1, visitor.instanceServlets.size());
  assertEquals(
      "wrong instance filters: " + visitor.instanceFilters, 1, visitor.instanceFilters.size());
}