什么是Dagger2
Dagger2是Android上的一個(gè)依賴注入框架萄涯,那么什么是依賴注入献幔,通俗一點(diǎn)來說就是我們不用去主動(dòng)創(chuàng)建(new)某個(gè)對(duì)象负甸,需要某個(gè)對(duì)象時(shí)妆毕,直接去Dagger2中去取即可慎玖,取個(gè)例子:
- 不使用依賴注入
<pre>
public class AActivity extends Activity {
private Account account;
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
// 這里需要使用到account對(duì)象,必須先創(chuàng)建account對(duì)象
account = new Account();
System.out.println(account);
}
}
</pre> - 使用依賴注入
<pre>
public class AActivity extends Activity {
// 如果需要使用依賴注入的形式笛粘,需要用到Inject的注解
@Inject
Account account;
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
// 在這里需要一些初始化的代碼趁怔,才能通過注解的形式創(chuàng)建account對(duì)象,這里主要描述什么是依賴注入薪前,后面再講這一塊
這是初始化dagger2的代碼
// 這里需要使用到account對(duì)象
System.out.println(account.toString());
// 如果dagger2的環(huán)境配置成功润努,這里是不會(huì)報(bào)錯(cuò)的
}
}
</pre>
不知道現(xiàn)在對(duì)dagger2的概念有沒有一定的了解。
Dagger2集成
dagger2的集成主要修改兩個(gè)文件
1示括、項(xiàng)目的build.gradle文件
<pre>
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
// 添加android-apt的支持
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
</pre>
2铺浇、module的build.gradle文件
<pre>
apply plugin: 'com.android.application'
// 應(yīng)用android-apt插件
apply plugin: 'com.neenbedankt.android-apt'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.yzd.dagger2demo"
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.dagger:dagger:2.0.2'
apt 'com.google.dagger:dagger-compiler:2.0.2'
compile 'org.glassfish:javax.annotation:10.0-b28' // dagger2用到的Java標(biāo)注
}
</pre>
Dagger2的簡(jiǎn)單用法
使用Dagger2至少需要用到下面四個(gè)注解:
- @Inject
用在變量上時(shí),表示該變量使用依賴注入垛膝;
用在構(gòu)造函數(shù)上時(shí)表示Dagger2使用該構(gòu)造函數(shù)實(shí)例化該對(duì)象 - @Component
一般使用在類上面:用來連接@Module和@Inject - @Module
一般使用在類上面:用來表示當(dāng)前類是為Dagger2提供實(shí)例的地方 - @Provides
用在@Module類的方法上面:表示Dagger2根據(jù)有@Provides的地方來實(shí)例化對(duì)象
另外還有一個(gè)比較常見的注解:
- @Singleton
用在類或者方法上面鳍侣,表示該類在Dagger2中是一個(gè)單例
下面開始使用Dagger2
1、創(chuàng)建一個(gè)Component接口吼拥,命名推薦用XXX+Component倚聚,并添加@Component注解,因?yàn)镃omponent是用來連接@Module和@Inject凿可,@Inject一般在Activity和其它我們需要用到的類中惑折,所以Component寫法如下
<pre>
@Component(modules = AppModule.class)
public interface ApplicationComponent {
void inject(DemoApplication application);
void inject(MainActivity mainActivity);
}
DemoApplication和MainActivity是我們需要采用依賴注入實(shí)例化對(duì)象的地方,
@Component的參數(shù)就是Dagger2實(shí)例化DemoApplication和MainActivity中@Inject標(biāo)注的對(duì)象的地方
</pre>
ApplicationComponent是一個(gè)接口,在編譯過程中Dagger2會(huì)生成這個(gè)接口的實(shí)現(xiàn)惨驶,該實(shí)現(xiàn)的類名為:Dagger + ApplicationComponent白热,即:Dagger + 接口的名稱。
DaggerApplicationComponent是我們后面需要使用的對(duì)象粗卜,所以我們?cè)趯懲闏omponent之后最好編譯一下屋确,編譯完成之后,我們會(huì)在module的build/generated/source/apt下面看到DaggerApplicationComponent這個(gè)類休建。
<p>
2、創(chuàng)建@Module類评疗,開始是一個(gè)空的類测砂,后面根據(jù)需要實(shí)例化的對(duì)象來添加相關(guān)依賴
<pre>
@Module
public class AppModule {
}
</pre>
3、創(chuàng)建實(shí)體對(duì)象
<pre>
public class User {
private String username;
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
</pre>
4百匆、根據(jù)實(shí)體對(duì)象來完善@Module類
<pre>
@Module
public class AppModule {
@Provides
public User provideUser() {
return new User("李四");
}
}
</pre>
5砌些、在Activity中使用依賴注入
<pre>
public class MainActivity extends AppCompatActivity {
@Inject
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerApplicationComponent.builder().appModule(new AppModule()).build().inject(this);
System.out.println(user.getUsername());
}
}
</pre>
DaggerApplicationComponent.builder().appModule(new AppModule()).build().inject(this);
這是一個(gè)固定寫法,其中加匈,appModule的方法是根據(jù)@Component中的參數(shù)AppModule.class的類名生成的一個(gè)方法存璃,方法參數(shù)為AppModule,如果你的Module名是其它的名稱雕拼,這里會(huì)變成相應(yīng)的名字纵东。
inject的方法名可以隨便取,推薦使用inject表示把當(dāng)前類注入到component中啥寇,返回值為void或者inject的參數(shù)
編譯運(yùn)行偎球,如果打印出"李四",就說明Dagger2就使用成功了辑甜。
如果想要User為單例衰絮,則在@Module中提供User的地方加上@Singleton注解,另外@Component也要添加@Singleton注解
6磷醋、如果實(shí)體的構(gòu)造函數(shù)需要依賴其它的類
當(dāng)上面的User在實(shí)例化時(shí)需要其它的對(duì)象猫牡,比如:Context,或者其它類邓线,的時(shí)候淌友,我們需要在@Module中也提供Context和其它類的@Provides的方法
<pre>
User類:
public class User {
private String username;
private Context context;
public User(Context context, String username) {
this.context = context;
this.username = username;
}
public String getUsername() {
return username + context.toString();
}
}
@Module類
Context需要外面?zhèn)鬟f進(jìn)來,所以為AppModule添加一個(gè)構(gòu)造函數(shù)
@Module
public class AppModule {
private Context mContext;
public AppModule(Context application) {
this.mContext = context;
}
@Provides
public Context provideContext() {
return mContext;
}
@Provides
public User provideUser(Context context) {
// 這里的context不能直接使用類的mContext
return new User(context, "李四");
}
}
MainActivity類
public class MainActivity extends AppCompatActivity {
@Inject
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerApplicationComponent.builder().appModule(new AppModule(getApplicationContext())).build().inject(this);
System.out.println(user.getUsername());
}
}
</pre>
如果User需要其它對(duì)象骇陈,跟上面情況類似亩进。
到這里Dagger2最基本的用法就介紹完了,希望對(duì)想入門Dagger2的朋友一個(gè)幫助缩歪。
有什么問題归薛,大家可以留言。