今天要接續來提有關Dagger中的Scope使用,那麼首先一樣先加入dagger需要的依賴至build.gradle中:
//dagger
implementation 'com.google.dagger:dagger:2.13'
annotationProcessor "com.google.dagger:dagger-compiler:2.13"
加入完依賴後便開始進入Scope的奧秘。
Scope(範圍),用於標示注入的使用範圍,其中@Singleton單例就是scope案例的一種,主要是可在相同範圍的作用域內提供相同的實例(只會有同一種實例),那麼接著先看到Singleton的原碼:
@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {}
看了Singleton的原碼後,便可開始自定義新的scope爾後套用至module和Component上,接著便修改成自己想設定的scope名稱(官方文件是比較建議將scope按照其生命週期命名):
@Scope
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MainScope {}
接著便可進行套用-->Component&Module
@MainScope
@Component(modules = MainModel.class)
public interface MainComponent {
void inject(MainActivity activity);
}
@Module
public class MainModel {
private int i;
private String s;
public MainModel(String s,int i){
this.s=s;
this.i=i;
}
@Provides
@MainScope
MainModel provideModel(@Named("stringS") String s,@Named("intI") int i){
return new MainModel(s,i);
}
@Named("intI")
@Provides
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Named("stringS")
@Provides
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
參考更多:Android Developers
接著先新增Second的di(SecondComponent、SecondModel、SecondScope):
@SecondScope
@Component(modules = SecondModel.class)
public interface SecondComponent {
void inject(Activity activity);
SecondModel getSecondModel();//提供出來
}
@Module
public class SecondModel {
private int i;
private String s;
public SecondModel(String s,int i){
this.s=s;
this.i=i;
}
@Provides
@SecondScope
SecondModel provideModel(@Named("stringS") String s, @Named("intI") int i){
return new SecondModel(s,i);
}
@Named("intI")
@Provides
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Named("stringS")
@Provides
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
@Scope
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface SecondScope {
}
大致上與Main的都很雷同,接著便開始設計主程式。
public class MainActivity extends AppCompatActivity {
@Inject
MainModel model;
MainComponent mainComponent;
SecondComponent secondComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondComponent = DaggerSecondComponent.builder().secondModel(new SecondModel("Second",2)).build();
//多層component
mainComponent=DaggerMainComponent.builder().mainModel(new MainModel("Str",0))
.secondComponent(secondComponent).build();
mainComponent.inject(this);
Log.d("Model","MainString:"+model.getS()+"\n" +
"MainInt:"+model.getI()+"\n"+
"SecondString:"+secondComponent.getSecondModel().getS()+"\n"+
"SecondInt:"+secondComponent.getSecondModel().getI());
}
}