com.google.inject.Key类的使用及代码示例

x33g5p2x  于2022-01-23 转载在 其他  
字(10.6k)|赞(0)|评价(0)|浏览(159)

本文整理了Java中com.google.inject.Key类的一些代码示例,展示了Key类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Key类的具体详情如下:
包路径:com.google.inject.Key
类名称:Key

Key介绍

[英]Binding key consisting of an injection type and an optional annotation. Matches the type and annotation at a point of injection.

For example, Key.get(Service.class, Transactional.class) will match:

@Inject 
public void setService( 
 @Transactional Service service) { 
... 
}

Key supports generic types via subclassing just like TypeLiteral.

Keys do not differentiate between primitive types (int, char, etc.) and their correpsonding wrapper types (Integer, Character, etc.). Primitive types will be replaced with their wrapper types when keys are created.
[中]由注入类型和可选注释组成的绑定键。在注入点匹配类型和注释。
例如,键。get(Service.class、Transactional.class)将匹配:

@Inject 
public void setService( 
 @Transactional Service service) { 
... 
}

键通过类似于TypeLiteral的子类化支持泛型类型。
键不区分基元类型(int、char等)及其对应的包装器类型(Integer、Character等)。在创建键时,基元类型将替换为它们的包装类型。

代码示例

代码示例来源:origin: prestodb/presto

public static Module simpleImpersonatingHdfsAuthenticationModule()
{
  return binder -> {
    binder.bind(Key.get(HadoopAuthentication.class, ForHdfs.class))
        .to(SimpleHadoopAuthentication.class);
    binder.bind(HdfsAuthentication.class)
        .to(ImpersonatingHdfsAuthentication.class)
        .in(SINGLETON);
  };
}

代码示例来源:origin: apache/incubator-druid

@SuppressWarnings("unchecked")
public static <T> void bindInstance(
  Binder binder,
  Key<T> bindKey,
  T instance
)
{
 binder.bind(bindKey).toInstance(instance);
 final ParameterizedType supType = Types.newParameterizedType(Supplier.class, bindKey.getTypeLiteral().getType());
 final Key supplierKey;
 if (bindKey.getAnnotationType() != null) {
  supplierKey = Key.get(supType, bindKey.getAnnotationType());
 } else if (bindKey.getAnnotation() != null) {
  supplierKey = Key.get(supType, bindKey.getAnnotation());
 } else {
  supplierKey = Key.get(supType);
 }
 binder.bind(supplierKey).toInstance(Suppliers.ofInstance(instance));
}

代码示例来源:origin: com.google.inject/guice

@Override
 public String toString(Key key) {
  if (key.getAnnotationType() != null) {
   return key.getTypeLiteral()
     + " annotated with "
     + (key.getAnnotation() != null ? key.getAnnotation() : key.getAnnotationType());
  } else {
   return key.getTypeLiteral().toString();
  }
 }
});

代码示例来源:origin: jenkinsci/jenkins

void error(Key<T> key, Throwable x) {
    if (verbose) {
      LOGGER.log(Level.WARNING, "Failed to instantiate " + key + "; skipping this component", x);
    } else {
      LOGGER.log(Level.INFO, "Failed to instantiate optional component {0}; skipping", key.getTypeLiteral());
      LOGGER.log(Level.FINE, key.toString(), x);
    }
  }
};

代码示例来源:origin: com.google.inject/guice

/**
 * Returns a key that doesn't hold any references to parent classes. This is necessary for
 * anonymous keys, so ensure we don't hold a ref to the containing module (or class) forever.
 */
public static <T> Key<T> canonicalizeKey(Key<T> key) {
 // If we know this isn't a subclass, return as-is.
 // Otherwise, recreate the key to avoid the subclass
 if (key.getClass() == Key.class) {
  return key;
 } else if (key.getAnnotation() != null) {
  return Key.get(key.getTypeLiteral(), key.getAnnotation());
 } else if (key.getAnnotationType() != null) {
  return Key.get(key.getTypeLiteral(), key.getAnnotationType());
 } else {
  return Key.get(key.getTypeLiteral());
 }
}

代码示例来源:origin: prestodb/presto

@Test
public void testExcludesCurrentNode()
    throws Exception
      .initialize();
  ServiceSelector selector = injector.getInstance(Key.get(ServiceSelector.class, serviceType("presto")));
  assertEquals(selector.selectAllServices().size(), 1);
  HeartbeatFailureDetector detector = injector.getInstance(HeartbeatFailureDetector.class);
  detector.updateMonitoredServices();
  assertEquals(detector.getTotalCount(), 0);
  assertEquals(detector.getActiveCount(), 0);
  assertEquals(detector.getFailedCount(), 0);
  assertTrue(detector.getFailed().isEmpty());

代码示例来源:origin: apache/incubator-druid

@Test
public void testMultiConditionalBind_cat()
{
 props.setProperty("animal.type", "cat");
 Injector injector = Guice.createInjector(new Module()
 {
  @Override
  public void configure(Binder binder)
  {
   ConditionalMultibind.create(props, binder, Animal.class)
             .addConditionBinding(ANIMAL_TYPE, Predicates.equalTo("cat"), Cat.class)
             .addConditionBinding(ANIMAL_TYPE, Predicates.equalTo("dog"), Dog.class);
  }
 });
 Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<Set<Animal>>()
 {
 }));
 Assert.assertEquals(1, animalSet.size());
 Assert.assertEquals(animalSet, ImmutableSet.<Animal>of(new Cat()));
}

代码示例来源:origin: apache/incubator-druid

@Override
 public Emitter apply(String s)
 {
  return injector.getInstance(Key.get(Emitter.class, Names.named(s)));
 }
}

代码示例来源:origin: apache/incubator-druid

@Override
 public void configure(Binder binder)
 {
  JsonConfigProvider.bindInstance(
    binder,
    Key.get(DruidNode.class, Self.class),
    node
  );
  binder.bind(Integer.class).annotatedWith(Names.named("port")).toInstance(node.getPlaintextPort());
  binder.bind(JettyServerInitializer.class).to(TestJettyServerInitializer.class).in(LazySingleton.class);
  Jerseys.addResource(binder, SimpleResource.class);
  LifecycleModule.register(binder, Server.class);
 }
}

代码示例来源:origin: Netflix/Priam

@BeforeClass
public static void setup() throws InterruptedException, IOException {
  new MockNodeProbe();
  injector = Guice.createInjector(new BRTestModule());
  filesystem =
      (FakeBackupFileSystem)
          injector.getInstance(
              Key.get(IBackupFileSystem.class, Names.named("backup")));
}

代码示例来源:origin: apache/incubator-druid

public ModuleList(Injector baseInjector)
{
 this.baseInjector = baseInjector;
 this.modulesConfig = baseInjector.getInstance(ModulesConfig.class);
 this.jsonMapper = baseInjector.getInstance(Key.get(ObjectMapper.class, Json.class));
 this.smileMapper = baseInjector.getInstance(Key.get(ObjectMapper.class, Smile.class));
 this.modules = new ArrayList<>();
}

代码示例来源:origin: apache/jclouds

@Test
public void testLinkedViewBindsViewAndContextSuppliers() {
 Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class))));
 assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient"))));
 assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient"))));
}

代码示例来源:origin: jclouds/legacy-jclouds

@AfterClass
private void close() throws IOException {
 ListeningExecutorService user = injector.getInstance(Key.get(ListeningExecutorService.class,
    named(PROPERTY_USER_THREADS)));
 ListeningExecutorService io = injector.getInstance(Key.get(ListeningExecutorService.class,
    named(PROPERTY_IO_WORKER_THREADS)));
 injector.getInstance(Closer.class).close();
 assertTrue(user.isShutdown());
 assertTrue(io.isShutdown());
}

代码示例来源:origin: apache/incubator-druid

@Override
public void configure(Binder binder)
{
 final MapBinder<String, Authorizer> authorizerMapBinder = PolyBind.optionBinder(
   binder,
   Key.get(Authorizer.class)
 );
 authorizerMapBinder.addBinding(AuthConfig.ALLOW_ALL_NAME).to(AllowAllAuthorizer.class).in(LazySingleton.class);
}

代码示例来源:origin: apache/incubator-druid

@Override
 public void configure(Binder binder)
 {
  binder.bind(RequestLogger.class).toProvider(RequestLoggerProvider.class).in(ManageLifecycle.class);
  binder.bind(Key.get(String.class, Names.named("serviceName"))).toInstance("some service");
  binder.bind(Key.get(Integer.class, Names.named("servicePort"))).toInstance(0);
  binder.bind(Key.get(Integer.class, Names.named("tlsServicePort"))).toInstance(-1);
  JsonConfigProvider.bind(binder, propertyPrefix, RequestLoggerProvider.class);
 }
}

代码示例来源:origin: apache/incubator-druid

@Override
 public void configure(Binder binder)
 {
  binder.bind(Key.get(String.class, Names.named("serviceName"))).toInstance("some service");
  binder.bind(Key.get(Integer.class, Names.named("servicePort"))).toInstance(0);
  binder.bind(Key.get(Integer.class, Names.named("tlsServicePort"))).toInstance(-1);
 }
}

代码示例来源:origin: apache/incubator-druid

public static void bindAnnouncer(
  final Binder binder,
  final Class<? extends Annotation> annotation,
  final DiscoverySideEffectsProvider provider
)
{
 binder.bind(DiscoverySideEffectsProvider.Child.class)
    .annotatedWith(annotation)
    .toProvider(provider)
    .in(LazySingleton.class);
 LifecycleModule.registerKey(binder, Key.get(DiscoverySideEffectsProvider.Child.class, annotation));
}

代码示例来源:origin: apache/incubator-druid

@Override
public void configure(Binder binder)
{
 JsonConfigProvider.bind(binder, "druid.monitoring", DruidMonitorSchedulerConfig.class);
 JsonConfigProvider.bind(binder, "druid.monitoring", MonitorsConfig.class);
 DruidBinders.metricMonitorBinder(binder); // get the binder so that it will inject the empty set at a minimum.
 binder.bind(DataSourceTaskIdHolder.class).in(LazySingleton.class);
 binder.bind(EventReceiverFirehoseRegister.class).in(LazySingleton.class);
 binder.bind(ExecutorServiceMonitor.class).in(LazySingleton.class);
 // Instantiate eagerly so that we get everything registered and put into the Lifecycle
 binder.bind(Key.get(MonitorScheduler.class, Names.named("ForTheEagerness")))
    .to(MonitorScheduler.class)
    .asEagerSingleton();
}

代码示例来源:origin: apache/incubator-druid

@Override
 public void configure(Binder binder)
 {
  createBindingChoices(binder, TYPE);
  super.configure(binder);

  binder.bind(MetadataStorage.class).toProvider(NoopMetadataStorageProvider.class);

  PolyBind.optionBinder(binder, Key.get(MetadataStorageProvider.class))
      .addBinding(TYPE)
      .to(DerbyMetadataStorageProvider.class)
      .in(LazySingleton.class);

  PolyBind.optionBinder(binder, Key.get(MetadataStorageConnector.class))
      .addBinding(TYPE)
      .to(DerbyConnector.class)
      .in(LazySingleton.class);

  PolyBind.optionBinder(binder, Key.get(SQLMetadataConnector.class))
      .addBinding(TYPE)
      .to(DerbyConnector.class)
      .in(LazySingleton.class);

  PolyBind.optionBinder(binder, Key.get(MetadataStorageActionHandlerFactory.class))
      .addBinding(TYPE)
      .to(DerbyMetadataStorageActionHandlerFactory.class)
      .in(LazySingleton.class);
 }
}

代码示例来源:origin: apache/incubator-druid

@Override
public void configure(Binder binder)
{
 Jerseys.addResource(binder, ChatHandlerResource.class);
 LifecycleModule.register(binder, ChatHandlerResource.class);
 if (properties.containsKey(MAX_CHAT_REQUESTS_PROPERTY)) {
  final int maxRequests = Integer.parseInt(properties.getProperty(MAX_CHAT_REQUESTS_PROPERTY));
  JettyBindings.addQosFilter(binder, "/druid/worker/v1/chat/*", maxRequests);
 }
 Multibinder.newSetBinder(binder, ServletFilterHolder.class).addBinding().to(TaskIdResponseHeaderFilterHolder.class);
 /**
  * We bind {@link DruidNode} annotated with {@link RemoteChatHandler} to {@literal @}{@link Self} {@link DruidNode}
  * so that same Jetty Server is used for querying as well as ingestion.
  */
 binder.bind(DruidNode.class).annotatedWith(RemoteChatHandler.class).to(Key.get(DruidNode.class, Self.class));
 binder.bind(ServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(ServerConfig.class));
 binder.bind(TLSServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(TLSServerConfig.class));
}

相关文章