加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 有人可以为Dagger 2提供一个很好的解释吗?

发布时间:2020-12-15 00:10:47 所属栏目:Java 来源:网络整理
导读:我真的很难理解匕首2依赖注入系统. 我明白使用@Inject注释告诉匕首我们需要提供一些类型的实例到这里. 但是,我不明白其他组件的各种角色,例如:@Module,@Component,@Provides以及它们如何协同工作,为适当的依赖关系提供适当的实例. 有人可以简单扼要地解释一
我真的很难理解匕首2依赖注入系统.

我明白使用@Inject注释告诉匕首我们需要提供一些类型的实例到这里.

但是,我不明白其他组件的各种角色,例如:@Module,@Component,@Provides以及它们如何协同工作,为适当的依赖关系提供适当的实例.

有人可以简单扼要地解释一下吗?

解决方法

@Module: Modules are classes whose methods provide dependencies,so we
define a class and annotate it with @Module,thus,Dagger will know
where to find the dependencies in order to satisfy them when
constructing class instances. One important feature of modules is that
they have been designed to be partitioned and composed together (for
instance we will see that in our apps we can have multiple composed
modules).

@Component: Components basically are injectors,let’s say a bridge between
@Inject and @Module,which its main responsibility is to put
both together. They just give you instances of all the types you
defined,for example,we must annotate an interface with @Component
and list all the @Modules that will compose that component,and if any
of them is missing,we get errors at compile time. All the components
are aware of the scope of dependencies it provides through its
modules.

@Provide: Inside modules we define methods containing this annotation
which tells Dagger how we want to construct and provide those
mentioned dependencies.

我建议你阅读:

> Tasting Dagger 2 on Android by Fernando Cejas
> Dependency Injection with Dagger 2 (Devoxx 2014) by Jake Wharton
> Dependency Injection with Dagger 2
> Dependency injection with Dagger 2 – the API by froger_mcs
> Dependency injection with Dagger 2 – Custom scopes by froger_mcs

我想这将有助于理解.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读