原文地址:https://code.google.com/p/google-guice/wiki/LinkedBindings
LinkedBindings(链接绑定):在类型上绑定它的实现。
贴代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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还可以写成绑定链,此时再添加个子类,
1 2 3 4 5 6 7 8 | public class SubHelloServiceImpl extends HelloServiceImpl { @Override public void sayHello() { System.out.println( "sub hello" ); } } |
然后,HelloServiceModule里注释打开。
执行结果:
SubHelloServiceImpl sub hello在写成绑定链时,injector返回该类型最终的实现类。