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

下面列出了怎么用com.google.inject.Binding的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: arcusplatform   文件: Injectors.java
public static <K, T> Map<K, T> mapInstancesOf(Injector injector, Class<T> type, final Function<T, K> keyFunction) {
	Preconditions.checkNotNull(injector, "injector");
	Preconditions.checkNotNull(type, "type");
	Preconditions.checkNotNull(keyFunction, "keyFunction");

	final Map<K, T> results = new LinkedHashMap<K, T>();
	visitBindings(injector, type, new BindingVisitor<T>() {
	   @Override
	   public void visit(Binding<T> binding) {
		   T value = binding.getProvider().get();
		   K key = keyFunction.apply(value);
		   results.put(key, value);
        }
	});
	return results;
}
 
源代码2 项目: n4js   文件: MultipleSingletonPluginUITest.java
private boolean isSingleton(Binding<?> b) {
	return b.acceptScopingVisitor(new DefaultBindingScopingVisitor<Boolean>() {
		@Override
		public Boolean visitEagerSingleton() {
			return Boolean.TRUE;
		}

		@Override
		public Boolean visitScope(Scope scope) {
			return Scopes.SINGLETON.equals(scope);
		}

		@Override
		protected Boolean visitOther() {
			return Boolean.FALSE;
		}
	});
}
 
源代码3 项目: seed   文件: SecurityModule.java
@Override
protected void configure() {
    for (Element element : privateElements.getElements()) {
        if (element instanceof Binding && isExcluded(((Binding<?>) element).getKey())) {
            continue;
        }
        element.applyTo(binder());
    }

    for (Key<?> exposedKey : privateElements.getExposedKeys()) {
        if (isExcluded(exposedKey)) {
            continue;
        }
        expose(exposedKey);
    }
}
 
源代码4 项目: 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;
}
 
源代码5 项目: 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());
}
 
源代码6 项目: 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());
}
 
源代码7 项目: gef   文件: AdapterInjector.java
/**
 * Infers the type of the given adapter, evaluating either the related
 * bindings or the runtime type of the adapter.
 *
 * @param adapterKey
 *            The key of the map binding, which is an {@link AdapterKey}.
 * @param binding
 *            The binding related to the {@link AdapterKey}.
 * @param adapter
 *            The adapter instance.
 * @param issues
 *            A list of issues that might be filled with error and warning
 *            messages.
 *
 * @return A {@link TypeToken} representing the type of the given adapter
 *         instance.
 */
private TypeToken<?> inferAdapterType(AdapterKey<?> adapterKey,
		Binding<?> binding, Object adapter, List<String> issues) {
	// try to infer the actual type of the adapter from the binding
	TypeToken<?> bindingInferredType = binding
			.acceptTargetVisitor(ADAPTER_TYPE_INFERRER);

	// perform some sanity checks
	validateAdapterBinding(adapterKey, binding, adapter,
			bindingInferredType, issues);

	// The key type always takes precedence. Otherwise, if we could
	// infer a type from the binding, we use that before falling back to
	// inferring the type from the adapter instance itself.
	TypeToken<?> bindingKeyType = adapterKey.getKey();
	return bindingKeyType != null ? bindingKeyType
			: (bindingInferredType != null ? bindingInferredType
					: TypeToken.of(adapter.getClass()));
}
 
源代码8 项目: pinpoint   文件: DefaultApplicationContextTest.java
@Test
public void test() {
    DefaultApplicationContext applicationContext = newApplicationContext();
    try {
        Injector injector = applicationContext.getInjector();
        Map<Key<?>, Binding<?>> bindings = injector.getBindings();
        for (Map.Entry<Key<?>, Binding<?>> e : bindings.entrySet()) {
            Key<?> key = e.getKey();
            Binding<?> binding = e.getValue();

            if (isPinpointBinding(key)) {
                boolean isSingletonScoped = Scopes.isSingleton(binding);
                Assert.assertTrue("Binding " + key + " is not Singleton scoped", isSingletonScoped);
            }
        }
        AgentInfoSender instance1 = injector.getInstance(AgentInfoSender.class);
        AgentInfoSender instance2 = injector.getInstance(AgentInfoSender.class);
        Assert.assertSame(instance1, instance2);
    } finally {
        applicationContext.close();
    }
}
 
源代码9 项目: dropwizard-guicey   文件: WebMappingsRenderer.java
private void renderGuiceWeb(final TreeNode filter) throws Exception {
    final List<String> servlets = new ArrayList<>();
    final List<String> filters = new ArrayList<>();

    for (Element element : Elements.getElements(Stage.TOOL, modules)) {
        if (!(element instanceof Binding)) {
            continue;
        }
        @SuppressWarnings("unchecked") final WebElementModel model =
                (WebElementModel) ((Binding) element).acceptTargetVisitor(VISITOR);
        if (model == null) {
            continue;
        }
        final String line = renderGuiceWebElement(model, element);
        if (model.getType().equals(WebElementType.FILTER)) {
            filters.add(line);
        } else {
            servlets.add(line);
        }
    }
    renderGucieWebElements(servlets, filters, filter);
}
 
源代码10 项目: seed   文件: ValidationModule.java
private Matcher<? super Binding<?>> staticValidationMatcher() {
    return new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> binding) {
            Class<?> candidate = binding.getKey().getTypeLiteral().getRawType();
            for (Field field : candidate.getDeclaredFields()) {
                for (Annotation annotation : field.getAnnotations()) {
                    if (hasConstraintOrValidAnnotation(annotation)) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
 
源代码11 项目: javalite   文件: Bootstrap.java
/**
 * Close all services from Guice that implement {@link Destroyable} interface.
 */
synchronized void destroy() {
    LOGGER.warn("Shutting off all services");
    Injector injector = getInjector();
    if (injector != null) {
        Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
        bindings.forEach((key, binding) -> {
            Provider p = binding.getProvider();
            if (p != null) {
                Object service = p.get();
                if (service != null) {
                    if (Destroyable.class.isAssignableFrom(service.getClass())) {
                        try {
                            LOGGER.warn("Shutting off: " + service);
                            ((Destroyable) service).destroy();
                        } catch (Exception ex) {
                            LOGGER.error("Failed to gracefully destroy " + service + ". Moving on to destroy the rest.", ex);
                        }
                    }
                }
            }
        });
    }
}
 
源代码12 项目: dropwizard-guicey   文件: BindingUtils.java
/**
 * Resolve binding declaration source string, if possible.
 *
 * @param binding binding
 * @return binding declaration source
 */
public static String getDeclarationSource(final Binding binding) {
    String res = "UNKNOWN";
    final Object source = binding.getSource();
    if (source instanceof ElementSource) {
        final ElementSource src = (ElementSource) source;
        StackTraceElement traceElement = null;
        if (src.getDeclaringSource() instanceof StackTraceElement) {
            traceElement = (StackTraceElement) src.getDeclaringSource();
        } else if (src.getDeclaringSource() instanceof Method) {
            traceElement = (StackTraceElement) StackTraceElements.forMember((Method) src.getDeclaringSource());
        }
        if (traceElement != null) {
            res = traceElement.toString();
        }
    } else if (source instanceof Class) {
        res = ((Class) source).getName();
    }
    return res;
}
 
源代码13 项目: dropwizard-guicey   文件: ModulesSupport.java
private static boolean checkBindingRemoveRequired(final ConfigurationContext context,
                                                  final Binding binding,
                                                  final List<Class<?>> extensions,
                                                  final Multimap<Key, LinkedKeyBinding> linkedBindings) {
    final Key key = binding.getKey();
    if (isPossibleExtension(key)) {
        context.stat().count(Stat.AnalyzedBindingsCount, 1);
        final Class type = key.getTypeLiteral().getRawType();
        if (ExtensionsSupport.registerExtensionBinding(context, type,
                binding, BindingUtils.getTopDeclarationModule(binding))) {
            LOGGER.debug("Extension detected from guice binding: {}", type.getSimpleName());
            extensions.add(type);
            return !context.isExtensionEnabled(type);
        }
    }
    // note if linked binding recognized as extension by its key - it would not be counted (not needed)
    if (binding instanceof LinkedKeyBinding) {
        // remember all linked bindings (do not recognize on first path to avoid linked binding check before
        // real binding)
        final LinkedKeyBinding linkedBind = (LinkedKeyBinding) binding;
        linkedBindings.put(linkedBind.getLinkedKey(), linkedBind);
    }
    return false;
}
 
源代码14 项目: arcusplatform   文件: Injectors.java
public static <T> T findInstanceOf(Injector injector, Class<T> type) {
	for(Binding<?> binding: collectBindings(injector)) {
		if(type.isAssignableFrom(binding.getKey().getTypeLiteral().getRawType())) {
			return (T) binding.getProvider().get();
		}
	}
	throw new IllegalStateException("No implementation of [" + type + "] found!");
}
 
源代码15 项目: arcusplatform   文件: Injectors.java
public static <T> List<T> listInstancesOf(Injector injector, Class<T> type) {
	final List<T> instances = new ArrayList<>();
	visitBindings(injector, type, new BindingVisitor<T>() {
	   @Override
	   public void visit(Binding<T> binding) {
	      instances.add(binding.getProvider().get());
	   }
	});
	return instances;
}
 
源代码16 项目: arcusplatform   文件: Injectors.java
private static <T> void visitBindings(
		final Injector injector,
		final Class<T> instanceOf,
		final BindingVisitor<T> visitor
) {
   for (Binding<?> binding : collectBindings(injector)) {
		Key<?> key = binding.getKey();
		if(instanceOf.isAssignableFrom(key.getTypeLiteral().getRawType())) {
			visitor.visit((Binding<T>) binding);
		}
   }
}
 
源代码17 项目: arcusplatform   文件: Injectors.java
private static List<Binding<?>> collectBindings(Injector injector) {
 List<Injector> injectors = new ArrayList<Injector>();
 Injector i = injector;
 while(i != null) {
 	injectors.add(0, i);
 	i = i != i.getParent() ? i.getParent() : null;
 }

 List<Binding<?>> bindings = new ArrayList<>();
 for(Injector i2: injectors) {
 	bindings.addAll(i2.getBindings().values());
 }
 return bindings;
}
 
源代码18 项目: sofa-ark   文件: ArkServiceContainer.java
/**
 * Start Ark Service Container
 * @throws ArkRuntimeException
 * @since 0.1.0
 */
public void start() throws ArkRuntimeException {
    if (started.compareAndSet(false, true)) {
        ClassLoader oldClassLoader = ClassLoaderUtils.pushContextClassLoader(getClass()
            .getClassLoader());
        try {
            LOGGER.info("Begin to start ArkServiceContainer");

            injector = Guice.createInjector(findServiceModules());
            for (Binding<ArkService> binding : injector
                .findBindingsByType(new TypeLiteral<ArkService>() {
                })) {
                arkServiceList.add(binding.getProvider().get());
            }
            Collections.sort(arkServiceList, new OrderComparator());

            for (ArkService arkService : arkServiceList) {
                LOGGER.info(String.format("Init Service: %s", arkService.getClass().getName()));
                arkService.init();
            }

            ArkServiceContainerHolder.setContainer(this);
            ArkClient.setBizFactoryService(getService(BizFactoryService.class));
            ArkClient.setBizManagerService(getService(BizManagerService.class));
            ArkClient.setInjectionService(getService(InjectionService.class));
            ArkClient.setEventAdminService(getService(EventAdminService.class));
            ArkClient.setArguments(arguments);
            LOGGER.info("Finish to start ArkServiceContainer");
        } finally {
            ClassLoaderUtils.popContextClassLoader(oldClassLoader);
        }

    }

}
 
源代码19 项目: n4js   文件: MultipleSingletonPluginUITest.java
private void getN4JSSingletonsOfInjector(Injector injector, Multimap<Class<?>, Injector> singletonInstances) {
	for (Binding<?> b : injector.getAllBindings().values()) {
		if (isSingleton(b)) {
			Key<?> key = b.getKey();
			TypeLiteral<?> typeLiteral = key.getTypeLiteral();
			String typeName = typeLiteral.toString();
			if (typeName.contains("n4js")) {
				singletonInstances.put(typeLiteral.getRawType(), injector);
			}
		}
	}
}
 
源代码20 项目: ProjectAres   文件: Injection.java
public static <T> Map<Key<? extends T>, Binding<? extends T>> bindingsAssignableTo(Injector injector, TypeToken<T> type) {
    final ImmutableMap.Builder<Key<? extends T>, Binding<? extends T>> builder = ImmutableMap.builder();
    forEachBinding(injector, binding -> {
        if(type.isAssignableFrom(binding.getKey().getTypeLiteral().getType())) {
            builder.put((Key<? extends T>) binding.getKey(), (Binding<? extends T>) binding);
        }
    });
    return builder.build();
}
 
源代码21 项目: ProjectAres   文件: Bindings.java
public static <T> Optional<TypeLiteral<? extends T>> targetType(Injector injector, Binding<T> binding) {
    if(binding instanceof UntargettedBinding) {
        return Optional.of(binding.getKey().getTypeLiteral());
    } else if(binding instanceof ConstructorBinding) {
        return Optional.of((TypeLiteral<? extends T>) ((ConstructorBinding) binding).getConstructor().getDeclaringType());
    } else if(binding instanceof InstanceBinding) {
        return Optional.of(TypeLiteral.get((Class<T>) ((InstanceBinding) binding).getInstance().getClass()));
    } else if(binding instanceof LinkedKeyBinding) {
        return targetType(injector, injector.getBinding(((LinkedKeyBinding) binding).getLinkedKey()));
    } else if(binding instanceof ExposedBinding) {
        return targetType(((ExposedBinding) binding).getPrivateElements().getInjector(), binding.getKey());
    }
    return Optional.empty();
}
 
源代码22 项目: ProjectAres   文件: Binders.java
default void installIn(Scoping scoping, Module... modules) {
    final Scoper scoper = new Scoper(this, scoping);
    for(Element element : Elements.getElements(modules)) {
        if(element instanceof Binding) {
            ((Binding) element).acceptTargetVisitor(scoper);
        } else {
            element.applyTo(this);
        }
    }
}
 
源代码23 项目: karyon   文件: KaryonAbstractInjectorGrapher.java
/**
 * Returns the bindings for the root keys and their transitive dependencies.
 */
private Iterable<Binding<?>> getBindings(Injector injector, Set<Key<?>> root) {
    Set<Key<?>> keys = Sets.newHashSet(root);
    Set<Key<?>> visitedKeys = Sets.newHashSet();
    List<Binding<?>> bindings = Lists.newArrayList();
    TransitiveDependencyVisitor keyVisitor = new TransitiveDependencyVisitor();

    while (!keys.isEmpty()) {
        Iterator<Key<?>> iterator = keys.iterator();
        Key<?> key = iterator.next();
        iterator.remove();

        if (!visitedKeys.contains(key)) {
            try {
                Binding<?> binding = injector.getBinding(key);
                bindings.add(binding);
                visitedKeys.add(key);
                keys.addAll(binding.acceptTargetVisitor(keyVisitor));
            }
            catch (ConfigurationException e) {
                System.out.println("Missing binding for : " + key);
                visitedKeys.add(key);
            }
        }
    }
    return bindings;
}
 
源代码24 项目: ProjectAres   文件: DependencyCollector.java
@Override
public <T> Object visit(Binding<T> binding) {
    requireKey(binding.getKey());
    explicitBindings.put(binding.getKey(), binding);
    binding.acceptTargetVisitor(new BindingVisitor<>());
    return super.visit(binding);
}
 
源代码25 项目: ProjectAres   文件: ElementUtils.java
public static <T> Optional<Binding<T>> findBinding(Iterable<? extends Element> elements, Key<T> key) {
    for(Element element : elements) {
        if(element instanceof Binding && key.equals(((Binding<?>) element).getKey())) {
            return Optional.of((Binding<T>) element);
        }
    }
    return Optional.empty();
}
 
源代码26 项目: greenbeans   文件: Application.java
@Override
public Set<Object> getSingletons() {
	ImmutableSet.Builder<Object> builder = ImmutableSet.<Object> builder();
	Map<Key<?>, Binding<?>> bindings = injector.getBindings();
	for (Key<?> key : bindings.keySet()) {
		if (hasAnnotation(key, ImmutableList.of(Path.class, Provides.class, Consumes.class)) && isEligible(key)) {
			builder.add(injector.getInstance(key));
		}
	}
	return builder.build();
}
 
源代码27 项目: greenbeans   文件: WebDispatch.java
private Map<WebPath, Handler> createPathToHandler(Injector injector) {
	ImmutableMap.Builder<WebPath, Handler> builder = ImmutableMap.builder();

	Map<Key<?>, Binding<?>> bindings = injector.getBindings();
	for (Entry<Key<?>, Binding<?>> entry : bindings.entrySet()) {
		Key<?> key = entry.getKey();
		if (isWebService(key)) {
			introspectWebService(builder, entry.getValue());
		}
	}

	return builder.build();
}
 
源代码28 项目: greenbeans   文件: WebDispatch.java
private void introspectWebService(Builder<WebPath, Handler> builder, Binding<?> binding) {
	Object webService = binding.getProvider().get();
	String basePath = webService.getClass().getAnnotation(Path.class).value();

	for (Method method : webService.getClass().getDeclaredMethods()) {
		for (Class<? extends Annotation> webMethodAnnotation : webMethodAnnotations) {
			Object annotation = method.getAnnotation(webMethodAnnotation);
			if (annotation != null) {
				introspectWebServiceMethod(builder, webMethodAnnotation.getSimpleName(), basePath, webService,
						method);
			}
		}
	}
}
 
源代码29 项目: greenbeans   文件: InjectorAsserts.java
public static <T> T assertSingletonBinding(Injector injector, Class<T> clazz) {
	Key<T> key = Key.get(clazz);
	Binding<T> binding = injector.getExistingBinding(key);
	assertNotNull(binding);
	T instance = injector.getInstance(key);
	assertSame(instance, injector.getInstance(key));
	return instance;
}
 
源代码30 项目: joynr   文件: DefaultJoynrRuntimeFactoryTest.java
@Test
public void testJoynrMessageProcessorAdded() throws Exception {
    createFixture();
    Injector injector = fixture.getInjector();
    List<Binding<JoynrMessageProcessor>> bindings = injector.findBindingsByType(new TypeLiteral<JoynrMessageProcessor>() {
    });
    assertEquals(1, bindings.size());
}
 
 类所在包
 同包方法