原文地址:https://code.google.com/p/google-guice/wiki/LinkedBindings
LinkedBindings(链接绑定):在类型上绑定它的实现。
贴代码
public interface HelloService { void sayHello(); } public class HelloServiceImpl implements HelloService { @Override public void sayHello() { System.out.println("hello"); } } import com.google.inject.AbstractModule; public class HelloServiceModule extends AbstractModule { @Override protected void configure() { bind(HelloService.class).to(HelloServiceImpl.class); // bind(HelloServiceImpl.class).to(SubHelloServiceImpl.class); } } public class Test { public static void main(String[] args) { Injector injector = Guice.createInjector(new HelloServiceModule()); HelloService helloService = injector.getInstance(HelloService.class); System.out.println(helloService.getClass().getSimpleName()); helloService.sayHello(); } }
执行结果:
HelloServiceImpl
hello
还可以写成绑定链,此时再添加个子类,
public class SubHelloServiceImpl extends HelloServiceImpl { @Override public void sayHello() { System.out.println("sub hello"); } }
然后,HelloServiceModule里注释打开。
执行结果:
SubHelloServiceImpl
sub hello
在写成绑定链时,injector返回该类型最终的实现类。