Dagger2系列:
Dagger版本:2.11
1. Module里添加subcomponents
上篇的结尾说到Module内可以再包含Component,需要注意的是,这个Component和之前的Component组件是不一样的
- 需要用@SubComponent注解
- SubComponent里面还需要再放一个Builder, interface或者abstract class都可以,标注@Subcomponent.Builder
- Builder里必须要有一个无参数的返回SubComponent本身的方法
- 如果SubComponent依赖其他Module,必须提供参数为这个Module,返回类型为Builder的方法(名字都叫Builder了,也就是建造者模式了,应该知道这是要干嘛了吧)
- Builder里的方法的方法名可随意,不过还是按规范走吧
先看看SubComponent注解类里的东西吧
/**
* A subcomponent that inherits the bindings from a parent {@link Component} or
* {@link Subcomponent}. The details of how to associate a subcomponent with a parent are described
* in the documentation for {@link Component}.
*
* @author Gregory Kick
* @since 2.0
*/
@Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger.
@Target(TYPE)
@Documented
public @interface Subcomponent {
/**
* A list of classes annotated with {@link Module} whose bindings are used to generate the
* subcomponent implementation. Note that through the use of {@link Module#includes} the full set
* of modules used to implement the subcomponent may include more modules that just those listed
* here.
*/
Class<?>[] modules() default {};
/**
* A builder for a subcomponent. This follows all the rules of {@link Component.Builder}, except
* it must appear in classes annotated with {@link Subcomponent} instead of {@code Component}.
* Components can have methods that return a {@link Subcomponent.Builder}-annotated type,
* allowing the user to set modules on the subcomponent using their defined API.
*/
@Target(TYPE)
@Documented
@interface Builder {}
}
大致意思是说子组件是继承父组件的,至于如何关联,在Component的文档里有说明
Subcomponents
The simplest way to relate two components is by declaring a Subcomponent. A subcomponent behaves exactly like a component, but has its implementation generated within a parent component or subcomponent. That relationship allows the subcomponent implementation to inherit the entire binding graph from its parent when it is declared. For that reason, a subcomponent isn't evaluated for completeness until it is associated with a parent.
Subcomponents are declared by listing the class in the Module.subcomponents() attribute of one of the parent component's modules. This binds the Subcomponent.Builder within the parent component.
Subcomponents may also be declared via a factory method on a parent component or subcomponent. The method may have any name, but must return the subcomponent. The factory method's parameters may be any number of the subcomponent's modules, but must at least include those without visible no-arg constructors. The following is an example of a factory method that creates a request-scoped subcomponent from a singleton-scoped parent:@Singleton @Component interface ApplicationComponent { // component methods... RequestComponent newRequestComponent(RequestModule requestModule); }
Component dependencies
While subcomponents are the simplest way to compose subgraphs of bindings, subcomponents are tightly coupled with the parents; they may use any binding defined by their ancestor component and subcomponents. As an alternative, components can use bindings only from another component interface by declaring a component dependency. When a type is used as a component dependency, each provision method on the dependency is bound as a provider. Note that only the bindings exposed as provision methods are available through component dependencies.
这里说下我的理解,英文太差很难看懂,如果有错误请各位大佬指正
-
子组件是完全继承父组件(一般的Component或者SubComponent都可以)的依赖关系
例如,子组件声明了给Target进行注入的方法,而Target有两个依赖MemberA和MemberB,子组件只注入了能够提供MemberB的模块,而父组件中注入了能提供MemberA的模块,这时子组件就可以通过父组件的模块实现Target中MemberA的注入 -
子组件的实例化必须要在父组件实例化完成之后
子组件本来就配置在父组件中的模块里了,自然只能等父组件实例化后才能获得 - 父组件需要声明提供子组件Builder的方法
示例:
class MemberA
@Module
class MemberAModule {
@Provides
fun provideMemberA(): MemberA = MemberA()
}
class MemberB
@Module
class MemberBModule {
@Provides
fun provideMemberB(): MemberB = MemberB()
}
class Member @Inject constructor(val memberA: MemberA, val memberB: MemberB)
class Target {
@Inject
lateinit var member: Member
}
@Subcomponent(modules = arrayOf(MemberBModule::class))
interface SubMemberComponent {
@Subcomponent.Builder
interface Builder {
// @Subcomponent里的modules写了什么模块,就得声明相对应的Builder模式的set方法
fun applyMemberBModule(module: MemberBModule): Builder
// 必须要有一个无参的,返回SubMemberComponent 本身的方法
fun build(): SubMemberComponent
}
// 子组件对外提供的方法,要是一个都不写,还要子组件干嘛
fun inject(target: Target)
}
这个SubComponent就是Module需要添加的子组件
// 添加了子组件后,这里声明的Provider或者是依赖这个模块的组件中的其他模块提供的Provider,在子组件中都能继承下来
@Module(includes = arrayOf(MemberAModule::class), subcomponents = arrayOf(SubMemberComponent::class))
class SubModule
// SubModule里的MemberAModule不写,写在这里也是可以的,dagger都能找到这个MemberA的提供者
@Component(modules = arrayOf(SubModule::class/*, MemberAModule::class*/))
interface TargetComponent {
// 对外提供子组件的Builder
fun getSubComponentBuilder(): SubMemberComponent.Builder
}
接下来看生成的代码
大体和之前差不多:
-
Member_Factory
:Member的工厂,Member依赖MemberA
和MemberB
,那么这个工厂就依赖MemberAModule_ProvideMemberAFactory
和MemberBModule_ProvideMemberBFactory
-
MemberAModule_ProvideMemberAFactory
:根据在MemberAModule
声明过提供MemberA
的方法生成的工厂 -
MemberBModule_ProvideMemberBFactory
:同样根据在MemberBModule
声明过提供MemberB
的方法生成的工厂 -
Target_MembersInjector
:没说好说的了,Provider齐全的注入器
重点看DaggerTargetComponent
,代码太多,不截图了
public final class DaggerTargetComponent implements TargetComponent {
private Provider<SubMemberComponent.Builder> subMemberComponentBuilderProvider;
private Provider<MemberA> provideMemberAProvider;
// 省略。。。
@Override
public SubMemberComponent.Builder getSubComponentBuilder() {
return subMemberComponentBuilderProvider.get();
}
private final class SubMemberComponentBuilder implements SubMemberComponent.Builder {
private MemberBModule memberBModule;
// 省略
}
private final class SubMemberComponentImpl implements SubMemberComponent {
private Provider<MemberB> provideMemberBProvider;
private Provider<Member> memberProvider;
private MembersInjector<Target> targetMembersInjector;
private SubMemberComponentImpl(SubMemberComponentBuilder builder) {
assert builder != null;
initialize(builder);
}
@SuppressWarnings("unchecked")
private void initialize(final SubMemberComponentBuilder builder) {
this.provideMemberBProvider =
MemberBModule_ProvideMemberBFactory.create(builder.memberBModule);
this.memberProvider =
Member_Factory.create(
DaggerTargetComponent.this.provideMemberAProvider, provideMemberBProvider);
this.targetMembersInjector = Target_MembersInjector.create(memberProvider);
}
@Override
public void inject(Target target) {
targetMembersInjector.injectMembers(target);
}
}
}
可以看到,DaggerTargetComponent
里面多了两个私有内部类,SubMemberComponentBuilder
就不说了,作用只是传入provideMemberBProvider
而已的,这里主要看SubMemberComponentImpl
的initialize
方法中的
this.memberProvider =
Member_Factory.create(
DaggerTargetComponent.this.provideMemberAProvider, provideMemberBProvider);
Member_Factory.create()
除了传入了SubMemberComponent
自身的provideMemberBProvider
外,还传入了属于DaggerTargetComponent
的provideMemberAProvider
,这就再次印证了前面的三点:
-
SubMemberComponent
是继承了父组件的依赖关系了(子组件的实现是父组件实现的内部类,可以直接调用父组件的Provider来作为自身的依赖关系) -
SubMemberComponent
只能依存于父组件DaggerTargetComponent
(内部类) -
SubMemberComponent
需要声明提供子组件Builder的方法getSubComponentBuilder
(没有在内部实例化子组件,需要外部提供MemberBModule
)
2.不在module中注入subComponent,直接写SubComponent
之前一直把子组件放在Module的subComponents里,而父组件里只能声明返回子组件Builder的方法,但我搜索过一堆子组件的写法,它们都是直接在父组件中声明返回子组件本身的,@Component的注释文档好像也提到过(跪舔英文T-T),只在官方的介绍页面看到过这种写Buidler的写法,那么接下来按这种不用声明Builder的方式再来一次
修改一下TargetComponent和SubMemberComponent
@Subcomponent(modules = arrayOf(MemberBModule::class))
interface SubMemberComponent {
fun inject(target: Target)
}
@Component(modules = arrayOf(MemberAModule::class/*, MemberBModule::class*/))
interface TargetComponent {
fun getSubMemberComponent(module: MemberBModule): SubMemberComponent
}
编译,生成的代码
呃。。。完全没区别?再看看DaggerTargetComponent
构造函数变了,传入的参数不是Builder了,而直接是MemberBModule。。。
呃。。。,总得来说,除此之外基本没区别,而且这种方式还不用在Subcomponent里写冗长的Builder代码,或许是后面版本做出的改进?或者是按本篇的例子,在某种情况下TargetComponent里拿不到MemberBModule的类型??,望知道的大佬指教。
3.总结:
本篇讲的是子组件SubComponent的两种写法,如果没特殊情况下,第二种写法是更加值得推荐的,省事省代码
那么使用SubComponent和Component中添加dependencies的区别是啥呢?
参考步骤 Dagger2 的 @Scope 和 @Subcomponent:
引用的是stackoverflow上的一个回答
Component Dependencies - Use this when:
// 你想保持两个组件之间的独立 you want to keep two components independent. // 你想强调一个组件是依赖于另一个组件 you want to explicitly show what dependencies from one component is used by the other.
Subcomponents - Use this when:
// 你想让一个组件保持高内聚(不想直接暴露子组件的实例化过程) you want to keep two component cohesive. // 你并不在意明确展示出两个组件之间的依赖关系(哪个组件依赖哪个组件) you may not care to explicitly show what dependencies from one component is used by the other.
SubComponent的作用
- 继承扩展功能并绑定生命周期
- 封装
最后是参考Dagger2 @Component 和@SubComponent 区别解惑:
Component Dependencies方案
优势
1.可以很清晰的看到Component生成时依赖于另外一个Component
2.有两个独立的DaggerXXXXComponent类需注意
Component仅能获取它依赖的Component中显式提供的依赖,如果不声明,则无法使用依赖的Component中的ProviderSubcomponents 方案
优势
1.不需要在父组件显式提供依赖
2.不需要使用更多的DaggerXXXXComponent对象来创建依赖
需注意
根据写法
1.要在父组件中声明返回子组件Builder的方法
2.要在父组件中声明返回子组件的方法(有子组件有的,父组件没有的模块时也需要作为参数声明)
参考资料
- [谷歌官方的介绍文档] https://google.github.io/dagger/subcomponents.html
- [步骤 Dagger2 的 @Scope 和 @Subcomponent]
http://www.zhimengzhe.com/Androidkaifa/163191.html - [Dagger2 入门解析] http://www.cnblogs.com/woshimrf/p/hello-dagger.html(http://www.cnblogs.com/woshimrf/p/hello-dagger.html
- [Dagger2 @Component 和@SubComponent 区别解惑]
http://blog.csdn.net/soslinken/article/details/70231089