0、相關文章:
參考此文:Android 神兵利器Dagger2使用詳解(二)Module&Component源碼分析
在我的上一篇文章中,我們通過Dagger2依賴注入的兩種方式獲取Student對象,並簡單瞭解了各個組件的作用和互相的聯繫:
@Inject : 注入,被註解的構造方法會自動編譯生成一個Factory工廠類提供該類對象。
@Component: 注入器,類似快遞員,作用是將產生的對象注入到需要對象的容器中,供容器使用。
@Module: 模塊,類似快遞箱子,在Component接口中通過@Component(modules =
xxxx.class),將容器需要的商品封裝起來,統一交給快遞員(Component),讓快遞員統一送到目標容器中。
本文我們繼續按照上文案例來講,通過源碼分析,看看究竟是爲什麼,我們能夠僅僅通過數個註解,就能隨心所欲使用Student對象。
1、代碼回顧
我們先不考慮Module,還是這樣的代碼:
1.1、Student類
public class Student {
@Inject
public Student() {
}
}
1.2、Module類
@Module
public class Test1Module {
private Test1Activity activity;
Test1Module(Test1Activity activity) {
this.activity = activity;
}
}
1.3、Component類
@Component(modules = Test1Module.class)
public interface Test1Component {
void inject(Test1Activity activity);
}
1.4、Activity類
public class Test1Activity extends AppCompatActivity {
@Inject
Student student;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
ButterKnife.bind(this);
initDatas();
}
private void initDatas() {
DaggerTest1Component.builder()
// .test1Module(new Test1Module(this))
.build()
.inject(this);
}
@OnClick(R.id.btn1)
public void onViewClicked() {
Toast.makeText(this, student.toString(), Toast.LENGTH_SHORT).show();
}
}
2、源碼解析
打開目錄結構:
我們不難發現,編譯器已經幫我們生成了這樣幾個文件:
- Student_Factory
- DaggerTest1Component
- Test1Activity_MembersInjector
- Test1Activity_ViewBinding(不用管,butterknife)
我們一一進行分析:
2.1、Student_Factory
上一篇文章我們已經進行了分析,很簡單,當我們@Inject註解一個類的構造方法時,編譯器會自動幫我們生成一個工廠類,負責生產該類的對象,類似於商品的廠家:
package com.gs.dagtest1.bean;
import dagger.internal.Factory;
public final class Student_Factory implements Factory<Student> {
private static final Student_Factory INSTANCE = new Student_Factory();
@Override
public Student get() {
return provideInstance();
}
public static Student provideInstance() {
return new Student();
}
public static Student_Factory create() {
return INSTANCE;
}
public static Student newStudent() {
return new Student();
}
}
2.2、DaggerTest1Component
public final class DaggerTest1Component implements Test1Component {
private DaggerTest1Component(Builder builder) {}
public static Builder builder() {
return new Builder();
}
public static Test1Component create() {
return new Builder().build();
}
@Override
public void inject(Test1Activity activity) {
injectTest1Activity(activity);
}
private Test1Activity injectTest1Activity(Test1Activity instance) {
Test1Activity_MembersInjector.injectStudent(instance, new Student());
return instance;
}
public static final class Builder {
private Builder() {}
public Test1Component build() {
return new DaggerTest1Component(this);
}
/**
* @deprecated This module is declared, but an instance is not used in the component. This
* method is a no-op. For more, see https://google.github.io/dagger/unused-modules.
*/
@Deprecated
public Builder test1Module(Test1Module test1Module) {
Preconditions.checkNotNull(test1Module);
return this;
}
}
}
2.3、Test1Activity_MembersInjector