为什么 Dagger 子组件是在模块中声明的,而不是直接在父组件中声明的?

Why are Dagger subcomponents declared in a module and not in the parent component directly?

为什么subcomponents =属性设置在组件的模块上,而不是直接在组件上?这对我来说似乎不是很直观,所以我想一定是有原因的。

@Component(modules = ExampleModule.class)
public interface AppComponent 

@Module(subcomponents = ActivityComponent.class)
public abstract class ExampleModule

从某种意义上说,子组件放在模块上更有意义:它们是私有的实现细节,不一定公开,公开的仍然可以直接在组件上列为构建器方法。为了便于比较,您也不能直接在组件上定义 @Provides@Binds 方法;这些也会影响组件的实现细节,不一定公开可见。

不过,你的观点是成立的;截至 2019 年 4 月 29 日,这是 an open and triaged issue (#1463),由 Google 撰稿人 David P. Baker 提交。

We see a pattern of people creating otherwise empty modules just to add subcomponents to components:

[...]

Propose adding subcomponents to dagger.Component, dagger.Subcomponent, dagger.producers.ProductionComponent, and dagger.producers.ProductionSubcomponent.

This would simplify these cases conceptually and reduce boilerplate because there is no need for an empty module.