简体   繁体   English

获取Guice中接口的实现类型

[英]Get the implementation type for an interface in Guice

I'm using Guice 3 to do dependency injection. 我正在使用Guice 3进行依赖项注入。

I have a particular use case where I need to know what implementation type has been bound to the interface. 我有一个特定的用例,在该用例中,我需要知道接口已绑定了哪种实现类型。 Is there a mechanism is Guice that allows us to do this? Guice是否有一种机制可以使我们做到这一点?

For such purposes Guice provides Extensions SPI. 为此,Guice提供了扩展SPI。

You need to extend the DefaultBindingTargetVisitor (if you wish to override selective methods) and override the visit(Binding binding) you wish to inspect. 您需要扩展DefaultBindingTargetVisitor(如果您希望覆盖选择性方法)并覆盖您要检查的visit(Binding绑定)。

public class MyBindingsVisitor extends DefaultBindingTargetVisitor<Object, String>{

    public String visit(InstanceBinding<? extends Object> binding){
        Key<? extends Object> key = binding.getKey();
            System.out.println("Key :" + key.getTypeLiteral());
            System.out.println("Annotation : " + key.getAnnotation());
            System.out.println("Source : " + binding.getSource());
            System.out.println("Instance : "+binding.getInstance().toString());
            return visitOther(binding);
    }
}

Now, we need the injector to visit the bindings. 现在,我们需要注入器访问绑定。

for(Binding<?> binding : injector.getBindings().values()){
    System.out.println(binding.acceptTargetVisitor(new MyBindingsVisitor()));
}

These bindings are complete bindings and hence are termed as the Injector Bindings. 这些绑定是完全绑定,因此被称为“注入器绑定”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM