本文整理了Java中com.google.inject.Binding
类的一些代码示例,展示了Binding
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Binding
类的具体详情如下:
包路径:com.google.inject.Binding
类名称:Binding
[英]A mapping from a key (type and optional annotation) to the strategy for getting instances of the type. This interface is part of the introspection API and is intended primarily for use by tools.
Bindings are created in several ways:
bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);
bindConstant().annotatedWith(ServerHost.class).to(args[0]);
They exist on both modules and on injectors, and their behaviour is different for each:
bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);
bindConstant().annotatedWith(ServerHost.class).to(args[0]);
*通过遵循类型的ImplementedBy ProvidedBy或使用其Inject或默认构造函数,由注入器隐式执行。
*通过将绑定实例转换为其他类型。
*对于提供程序,通过委托给所提供类型的绑定。
它们存在于两个模块和喷油器上,它们的行为各不相同:
*模块绑定不完整,无法用于提供实例。这是因为在创建注入器之前,可能不知道适用的作用域和拦截器。从工具的角度来看,模块绑定类似于注入器的源代码。它们可以被检查或重写,但这种分析必须静态进行。
*注入器绑定完整有效,可用于提供实例。从工具的角度来看,注入器绑定就像是注入器的反射。它们具有完整的运行时信息,包括满足绑定所需的完整注入图。
代码示例来源:origin: bootique/bootique
private static Optional<Command> defaultCommand(Injector injector) {
// default is optional, so check via injector whether it is bound...
Binding<Command> binding = injector.getExistingBinding(Key.get(Command.class, DefaultCommand.class));
return binding != null ? Optional.of(binding.getProvider().get()) : Optional.empty();
}
代码示例来源:origin: apache/incubator-druid
private Emitter findEmitter(String emitterType, List<Binding<Emitter>> emitterBindings)
{
for (Binding<Emitter> binding : emitterBindings) {
if (Names.named(emitterType).equals(binding.getKey().getAnnotation())) {
return binding.getProvider().get();
}
}
return null;
}
代码示例来源:origin: com.google.inject/guice
TypeLiteral<T> type = key.getTypeLiteral();
List<Binding<T>> sameTypes = injector.findBindingsByType(type);
if (!sameTypes.isEmpty()) {
sb.append(format("%n Did you mean?"));
sb.append(format("%n * %s", sameTypes.get(i).getKey()));
String want = type.toString();
Map<Key<?>, Binding<?>> bindingMap = injector.getAllBindings();
for (Key<?> bindingKey : bindingMap.keySet()) {
String have = bindingKey.getTypeLiteral().toString();
if (have.contains(want) || want.contains(have)) {
Formatter fmt = new Formatter();
Messages.formatSource(fmt, bindingMap.get(bindingKey).getSource());
String match = String.format("%s bound%s", convert(bindingKey), fmt.toString());
possibleMatches.add(match);
&& key.getAnnotation() == null
&& COMMON_AMBIGUOUS_TYPES.contains(key.getTypeLiteral().getRawType())) {
代码示例来源:origin: com.google.inject/guice
@Override
protected void doInitialize(InjectorImpl injector, Errors errors) {
ImmutableMap.Builder<K, Provider<V>> mapOfProvidersBuilder = ImmutableMap.builder();
ImmutableSet.Builder<Dependency<?>> dependenciesBuilder = ImmutableSet.builder();
for (Map.Entry<K, Binding<V>> entry : bindingSelection.getMapBindings().entrySet()) {
mapOfProvidersBuilder.put(entry.getKey(), entry.getValue().getProvider());
dependenciesBuilder.add(Dependency.get(getKeyOfProvider(entry.getValue().getKey())));
}
mapOfProviders = mapOfProvidersBuilder.build();
dependencies = dependenciesBuilder.build();
}
代码示例来源:origin: com.google.inject/guice
@Override
public <T> Void visit(Binding<T> binding) {
if (!overriddenKeys.remove(binding.getKey())) {
super.visit(binding);
// Record when a scope instance is used in a binding
Scope scope = getScopeInstanceOrNull(binding);
if (scope != null) {
List<Object> existing = scopeInstancesInUse.get(scope);
if (existing == null) {
existing = Lists.newArrayList();
scopeInstancesInUse.put(scope, existing);
}
existing.add(binding.getSource());
}
}
return null;
}
代码示例来源:origin: com.google.inject.extensions/guice-servlet
final FilterDefinition filterDef =
new FilterDefinition(
Key.get(Filter.class),
UriPatternType.get(UriPatternType.SERVLET, pattern),
new HashMap<String, String>(),
expect(injector.getBinding(Key.get(Filter.class))).andReturn(binding);
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
expect(injector.getInstance(Key.get(Filter.class))).andReturn(mockFilter).anyTimes();
代码示例来源:origin: com.google.inject.extensions/guice-servlet
final ServletDefinition servletDefinition =
new ServletDefinition(
Key.get(HttpServlet.class),
UriPatternType.get(UriPatternType.SERVLET, pattern),
new HashMap<String, String>(),
expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(mockServlet);
final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral())))
.andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
expect(mockBinding.getProvider()).andReturn(bindingProvider);
代码示例来源:origin: ArcBees/Jukito
methodInjector = Guice.createInjector(jukitoModule);
if (!All.class.equals(key.getAnnotationType())) {
injectedParameters.add(methodInjector.getInstance(key));
} else {
if (!bindingIter.hasNext()) {
throw new AssertionError("Expected more bindings to fill @All parameters.");
injectedParameters.add(methodInjector.getInstance(bindingIter.next().getKey()));
代码示例来源:origin: eclipse/kapua
@Override
public List<KapuaService> getServices() {
final List<KapuaService> servicesList = new ArrayList<>();
final Map<Key<?>, Binding<?>> bindings = injector.getBindings();
for (Binding<?> binding : bindings.values()) {
final Class<?> clazz = binding.getKey().getTypeLiteral().getRawType();
if (KapuaService.class.isAssignableFrom(clazz)) {
servicesList.add(injector.getInstance(clazz.asSubclass(KapuaService.class)));
}
}
return servicesList;
}
代码示例来源:origin: com.google.inject.extensions/guice-assistedinject
Key.get(Integer.class),
Key.get(Double.class),
Key.get(Float.class),
Key.get(String.class, named("dog")),
Key.get(String.class, named("cat1")),
Key.get(String.class, named("cat2")),
Key.get(String.class, named("cat3")));
Injector injector = Guice.createInjector(module);
validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
injector = Guice.createInjector(Stage.TOOL, module);
validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
if (element instanceof Binding) {
Binding<?> binding = (Binding<?>) element;
if (binding.getKey().equals(Key.get(AnimalHouse.class))) {
found = true;
validateDependencies(expectedKeys, binding);
代码示例来源:origin: jenkinsci/jenkins
private <U> void _find(Class<U> type, List<ExtensionComponent<U>> result, Injector container) {
for (Entry<Key<?>, Binding<?>> e : container.getBindings().entrySet()) {
if (type.isAssignableFrom(e.getKey().getTypeLiteral().getRawType())) {
Annotation a = annotations.get(e.getKey());
Object o = e.getValue().getProvider().get();
if (o!=null) {
GuiceExtensionAnnotation gea = a!=null ? extensionAnnotations.get(a.annotationType()) : null;
result.add(new ExtensionComponent<>(type.cast(o), gea != null ? gea.getOrdinal(a) : 0));
}
}
}
}
代码示例来源:origin: org.eclipse.sisu/org.eclipse.sisu.inject.tests
final BindingPublisher exporter3 = new InjectorPublisher( injector3, new DefaultRankingFunction( 3 ) );
final RankedBindings<Bean> bindings = new RankedBindings<Bean>( TypeLiteral.get( Bean.class ), null );
assertNull( explicitBinding.getKey().getAnnotation() );
assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) );
bindings.remove( injector3.findBindingsByType( TypeLiteral.get( Bean.class ) ).get( 0 ) );
bindings.remove( exporter2 );
bindings.remove( injector1.findBindingsByType( TypeLiteral.get( Bean.class ) ).get( 0 ) );
assertNull( explicitBinding.getKey().getAnnotation() );
assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) );
assertEquals( Names.named( "3" ), itr.next().getKey().getAnnotation() );
assertTrue( itr.hasNext() );
assertEquals( Names.named( "2" ), itr.next().getKey().getAnnotation() );
assertTrue( itr.hasNext() );
assertEquals( Names.named( "1" ), itr.next().getKey().getAnnotation() );
代码示例来源:origin: ninjaframework/ninja
@Override
public Object visitEagerSingleton() {
injector.getInstance(binding.getKey());
return null;
}
代码示例来源:origin: apache/incubator-druid
@BeforeClass
public static void populateStatics()
{
injector = GuiceInjectors.makeStartupInjectorWithModules(ImmutableList.<com.google.inject.Module>of(new CacheConfigTestModule()));
configurator = injector.getBinding(JsonConfigurator.class).getProvider().get();
}
代码示例来源:origin: org.jbehave/jbehave-guice
private void addInstances(Injector injector, Class<?> type, List<Object> instances) {
for (Binding<?> binding : injector.getBindings().values()) {
Key<?> key = binding.getKey();
if (type.equals(key.getTypeLiteral().getType())) {
instances.add(injector.getInstance(key));
}
}
if (injector.getParent() != null) {
addInstances(injector.getParent(), type, instances);
}
}
}
代码示例来源:origin: datacleaner/DataCleaner
/**
* Creates an {@link Injector} which in turn can be used to get instances of
* various types.
*
* Note the the {@link #getInstance(Class)} method is preferred, if only a
* single injection is to be made.
*
* @return a Guice injector
*/
public Injector createInjector() {
for (final TypeLiteral<?> typeLiteral : _inheritedTypeLiterals) {
final Key<?> key = Key.get(typeLiteral);
final Binding<?> binding = _parentInjector.getExistingBinding(key);
if (binding != null) {
if (!_adHocModule.hasBindingFor(typeLiteral)) {
// Bind entry if not already bound in adhoc module!!!
_adHocModule.bind(typeLiteral, binding.getProvider());
}
}
}
final Module module = Modules.override(_parentModule).with(_adHocModule);
return Guice.createInjector(module);
}
}
代码示例来源:origin: alipay/sofa-ark
LOGGER.info("Begin to start ArkServiceContainer");
injector = Guice.createInjector(findServiceModules());
for (Binding<ArkService> binding : injector
.findBindingsByType(new TypeLiteral<ArkService>() {
})) {
arkServiceList.add(binding.getProvider().get());
代码示例来源:origin: apache/incubator-druid
throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException
JsonConfigurator configurator = injector.getBinding(JsonConfigurator.class).getProvider().get();
Assert.assertEquals(propertyValues.size(), assertions);
ObjectMapper jsonMapper = injector.getProvider(Key.get(ObjectMapper.class, Json.class)).get();
String jsonVersion = jsonMapper.writeValueAsString(zkPathsConfigObj);
代码示例来源:origin: net.stickycode.configured/sticky-configured-guice3
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object findWithName(Class contract, String name) throws StrategyNotFoundException {
Binding<Set> b = injector.getBinding(Key.get(setOf(TypeLiteral.get(contract))));
for (Object o : b.getProvider().get()) {
if (name.equals(Introspector.decapitalize(o.getClass().getSimpleName())))
return o;
}
throw new StrategyNotFoundException(contract, name, Collections.<String>emptySet());
}
代码示例来源:origin: com.google.inject.extensions/guice-servlet
public final void testSpiOnInjector() {
ServletSpiVisitor visitor = new ServletSpiVisitor(true);
int count = 0;
Injector injector = Guice.createInjector(new Module());
for (Binding binding : injector.getBindings().values()) {
assertEquals(count++, binding.acceptTargetVisitor(visitor));
}
validateVisitor(visitor);
}
内容来源于网络,如有侵权,请联系作者删除!