http://superleo.iteye.com/blog/314816
Private Modules
PrivateModules 用于创建并不需要对外可见的绑定对象。当然,这样会使得封装变得更加简单,还避免了冲突。
作者没有写关于 PrivateModules 的内容,有可能还没有更新完吧。我们就简单看一个例子:
Java代码
- public class FooBarBazModule extends PrivateModule {
- protected void configurePrivateBindings() {
- bind(Foo.class).to(RealFoo.class);
- expose(Foo.class); //expose方法用于向外部暴露内部的绑定Foo
- install(new TransactionalBarModule()); //install方法允许将本PrivateModule模块嵌入到TransactionalBarModule模块中去。
- expose(Bar.class).annotatedWith(Transactional.class); //expose方法用于向外部暴露内部的绑定Bar,并令其标注为Transactional
- bind(SomeImplementationDetail.class);
- install(new MoreImplementationDetailsModule());
- }
- //向外部暴露的方法
- @Provides @Exposed
- public Baz provideBaz() {
- return new SuperBaz();
- }
- }
com.google.inject.PrivateModule
A module whose configuration information is hidden from its environment by default. Only bindings that are explicitly exposed will be available to other modules and to the users of the injector. This module may expose the bindings it creates and the bindings of the modules it installs.
A private module can be nested within a regular module or within another private module using install()
. Its bindings live in a new environment that inherits bindings, type converters, scopes, and interceptors from the surrounding ("parent") environment. When you nest multiple private modules, the result is a tree of environments where the injector‘s environment is the root.
Guice EDSL bindings can be exposed with expose()
. @Provides
bindings can be exposed with the @Exposed
annotation:
public class FooBarBazModule extends PrivateModule { protected void configure() { bind(Foo.class).to(RealFoo.class); expose(Foo.class); install(new TransactionalBarModule()); expose(Bar.class).annotatedWith(Transactional.class); bind(SomeImplementationDetail.class); install(new MoreImplementationDetailsModule()); } @Provides @Exposed public Baz provideBaz() { return new SuperBaz(); } }
Private modules are implemented using parent injectors
. When it can satisfy their dependencies, just-in-time bindings will be created in the root environment. Such bindings are shared among all environments in the tree.
The scope of a binding is constrained to its environment. A singleton bound in a private module will be unique to its environment. But a binding for the same type in a different private module will yield a different instance.
A shared binding that injects the Injector
gets the root injector, which only has access to bindings in the root environment. An explicit binding that injects the Injector
gets access to all bindings in the child environment.
To promote a just-in-time binding to an explicit binding, bind it:
bind(FooImpl.class);
- Since:
- 2.0
- Author:
- [email protected] (Jesse Wilson)