下面列出了怎么用com.google.inject.Binding的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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;
}
});
}
@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);
}
}
@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;
}
@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());
}
@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());
}
/**
* 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()));
}
@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();
}
}
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);
}
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;
}
};
}
/**
* 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);
}
}
}
}
});
}
}
/**
* 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;
}
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;
}
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!");
}
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;
}
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);
}
}
}
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;
}
/**
* 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);
}
}
}
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);
}
}
}
}
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();
}
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();
}
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);
}
}
}
/**
* 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;
}
@Override
public <T> Object visit(Binding<T> binding) {
requireKey(binding.getKey());
explicitBindings.put(binding.getKey(), binding);
binding.acceptTargetVisitor(new BindingVisitor<>());
return super.visit(binding);
}
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();
}
@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();
}
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();
}
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);
}
}
}
}
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;
}
@Test
public void testJoynrMessageProcessorAdded() throws Exception {
createFixture();
Injector injector = fixture.getInjector();
List<Binding<JoynrMessageProcessor>> bindings = injector.findBindingsByType(new TypeLiteral<JoynrMessageProcessor>() {
});
assertEquals(1, bindings.size());
}