Guice绑定概述 Bindings
Guice绑定概述
Overview of bindings in Guice
绑定 Bindings
注射器的作用是“绘制”对象关系图。当你需要某个类型的实例时,它会知道如何构建,如何处理依赖关系,并把他们关联在一起。下面将介绍依赖是怎么实现的,如何配置绑定。
The injector’s job is to assemble graphs of objects. You request an instance of a given type, and it figures out what to build, resolves dependencies, and wires everything together. To specify how dependencies are resolved, configure your injector with bindings.
创建绑定的时候,我们需要继承一个抽象的Module(AbstractModule),并且重写configure方法。在方法体中,调用bind()方法进行绑定。被绑定的方法需要类型一致,否则编译器会报错。当创建完module后,就可以通过参数传递给 Guice.createInjector()方法实现注入了。
创建绑定Creating Bindings
To create bindings, extend AbstractModule and override its configure method. In the method body, call bind() to specify each binding. These methods are type checked so the compiler can report errors if you use the wrong types. Once you’ve created your modules, pass them as arguments to Guice.createInjector() to build an injector.
用modules创建链接绑定(linked bind),实例绑定(instance bindings),@Provides方法,提供者绑定(provider bindings),构造函数绑定(constructor bindings),无目标绑定(untargeted bindings)。
Use modules to create linked bind, instance bindings, @Provides methods, provider bindings, constructor bindings and untargeted bindings.
更多 More Bindings
除了上述这些绑定方式,你还能指定内部绑定(built-in bindings)。当一个依赖找不到时,它会尝试创建一个即时绑定(just-in-time binding)。注入器还包括其他绑定提供者
In addition to the bindings you specify the injector includes built-in bindings. When a dependency is requested but not found it attempts to create a just-in-time binding. The injector also includes bindings for the providers of its other bindings.
发表评论
难的是和自己保持联系~