您的位置:首页 > 其它

依赖注入 Dagger 2学习

2015-12-30 22:48 141 查看
参考:

1. Dagger2 基础注入(极大促进理解)

2. 官方文档

3. Dagger 2 on Android 前半部分

4. Dagger 2 - the API

使用配置

项目根project.gradle内dependencies中添加classpath:

dependencies{
classpath'com.android.tools.build:gradle:1.5.0'//gradle 版本号
classpath'com.neenbedankt.gradle.plugins:android-apt:1.4'
}


gradle(app)中添加apt插件:

apply plugin: 'com.neenbedankt.android-apt'


gradle(app)中添加compile:

apt 'com.google.dagger:dagger-compiler:2.0'
compile 'com.google.dagger:dagger:2.0'
provided 'javax.annotation:jsr250-api:1.0'


Dagger2注解介绍

@Inject:Declaring Dependencies

声明依赖。注入器,标识被注入的对象。会调用其构造方法来创建对象

Use @Inject to annotate the constructor that Dagger should use to create instances of a class.

When a new instance is requested, Dagger will obtain the required parameters values and invoke this constructor.

Dagger can inject fields directly.

给无参构造函数添加@Inject注解则会创建其对象

If your class has @Inject-annotated fields but no @Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the @Inject annotation to indicate that Dagger may create instances as well.

@Provides :satisfy a dependency.

提供依赖,所有的Provides方法必须属于Module

provideXxx() is invoked whenever a Xxx is required.It contact with the @Inject

@Module:Modules are classes whose methods provide dependencies

@Component:an Interface

连接依赖和消费依赖的组件

annotate to such an interface and passing the module types to the modules parameter, Dagger 2 can form a fully object graph.

接口实现类:The implementation has the same name as the interface prefixed with Dagger. Obtain an instance by invoking the builder() method on that implementation and use the returned builder to set dependencies and build() a new instance.

简写:Any module with an accessible default constructor can use .create() to initiate an instance.

@Singleton:单例

The graph will use a single instance of the value for all of its clients. It can decorate the @Provides and the class.

Dagger 2特殊

Lazy injections :Lazy< T >

懒加载

you can create a Lazy which defers instantiation until the first call to Lazy< T >’s get() method

Provider injections

命名规范:

@Provides methods are named with a provide prefix

@Module classes are named with a Module suffix.

需要继续理解的:

Scope

Provider injections

自定义注解 Qualifiers

还需要在实战中增强理解

单方面理解概念总会忘记,不能形成全貌。不太理解所谓的ObjectGraph怎么形成的,依赖之间的相互依赖,提供依赖的还要消费别的依赖。所以从生成代码上理解下,可能对以后大有帮助。

打断点会帮助理解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: