前言
Dagger解决android中的依赖注入问题,即实现控制反转(IoC)技术,Ioc的主要目的是一个类应该从外部获取自身的依赖。
Dagger1 含2个缺点:1,因为反射,使得自己变慢;2,使用运行时依赖解决方案,会导致异常崩溃。
依赖注入的优点:提高类的重用性和能够独立于其他类来测试他们。
注入模式:
1.构造器注入:注入方法参数。
2.字段注入:注入成员变量。
3.方法注入:注入方法参数。
依赖注入顺序:
1.构造器
2.字段
3.方法
Dagger2 的结构:
依赖端通过连接器从依赖提供者请求依赖对象。
- 依赖提供者:使用原语@Module声明的类,此类的方法用原语@Provides来定义
- 依赖客户端:用原语@Inject来表示一个依赖。
- 客户端与生产器之间的连接器:原语@Component定义,此类是Dagger生成的连接器。
Dagger2的不足:
- 不能自动注入字段
- 不能注入私有字段
- 如果要使用字段注入,必须在连接器中定义方法
本文翻译至Introduction to Dagger 2, Using Dependency Injection in Android: Part 1,翻译有误,还请看原文。
Dagger 2 uses the following annotations
- Provider:- classes with annotated with @Module is responsible for providing an object which can be injected.
带 @Module注解的类负责提供可注入对象。 - Consumer:- The @Inject annotation is used to defining a dependency.
带 @Inject注解是用来定义依赖 - Connector:- A @Component annotated interface defines the connection between the provider and consumer.
@Component注解接口定义供给端与消费端的的关联。