链接绑定 Linked Bindings
Guice中最常用的一种绑定为Linked Bindings,或者起名为链接绑定。
链接绑定是指把一个类型映射到它的一个具体实现上。下面这个例子就是把接口(TransactionLog )映射到它的一个实现上(DatabaseTransactionLog):
Linked bindings map a type to its implementation. This example maps the interface TransactionLog to the implementation DatabaseTransactionLog:
1 2 3 4 5 6 |
public class BillingModule extends AbstractModule { @Override protected void configure() { bind(TransactionLog.class).to(DatabaseTransactionLog.class); } } |
当你执行 injector.getInstance(TransactionLog.class)调用,或者injector遇到依赖于TransactionLog时,那么程序将实际使用DatabaseTransactionLog。可以将类型“链接”(映射)到它的任意子类型上,比如链接到它的一个实现类或一个扩展类上。你甚至还可以把具体的DatabaseTransactionLog 类(不是接口)链接到它的子类上。
Now, when you call injector.getInstance(TransactionLog.class), or when the injector encounters a dependency on TransactionLog, it will use a DatabaseTransactionLog. Link from a type to any of its subtypes, such as an implementing class or an extending class. You can even link the concrete DatabaseTransactionLog class to a subclass:
1 |
bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class); |
这种链接绑定可以是“链式”串联的:
Linked bindings can also be chained:
1 2 3 4 5 6 7 |
public class BillingModule extends AbstractModule { @Override protected void configure() { bind(TransactionLog.class).to(DatabaseTransactionLog.class); bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class); } } |
在这种情况下,当需要TransactionLog类型的值时,注入器提供的是MySqlDatabaseTransactionLog类型的值。
In this case, when a TransactionLog is requested, the injector will return a MySqlDatabaseTransactionLog.
实例
1 2 3 4 5 6 7 8 9 10 11 |
public interface HelloService { void sayHello(); } public class HelloServiceImpl implements HelloService { @Override public void sayHello() { System.out.println("hello"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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 |
public class SubHelloServiceImpl extends HelloServiceImpl { @Override public void sayHello() { System.out.println("Sub Hello"); } } |
然后将之前HelloServiceModule里的注释去掉。
执行结果:
SubHelloServiceImpl
Sub Hello
实例参考来源:http://lifestack.cn/archives/85.html
下一节:绑定注释 Binding Annotations
说明:
鉴于网上guice中文资料较少,出于个人爱好,对该项目下的用户API文档进行翻译。如有翻译不恰当之处,还望指正。
google Guice 项目地址:https://github.com/google/guice
Guice 英文API地址:https://github.com/google/guice/wiki/LinkedBindings
发表评论
难的是和自己保持联系~