Android Dagger2入门详解(六)
来源:互联网 发布:阿里云服务器配置推荐 编辑:程序博客网 时间:2024/06/04 19:29
组件依赖(继承)
新增AppModule:
@Modulepublic class AppModule { private Context context; public AppModule(Context context) { this.context = context; } @Provides public Context providesContext() { return context; }}
新增AppComponent:
@Component(modules = {AppModule.class})public interface AppComponent { // 向下层提供Context Context getContext();}
修改CarModule:
@Modulepublic class CarModule {// private Context context;// @Provides// static Car provideCar(){// return new Car("My New Car");// }// public CarModule(Context context) {// this.context = context;// } @Provides static Car provideCar(String name){ return new Car(name); } @Singleton @Named("Car1") @Provides static Car provideCar1(){ return new Car("My Car1"); } @Named("Car2") @Provides static Car provideCar2(){ return new Car("My Car2"); } @CarWithContext @Provides static Car provideCar3(Context context){ return new Car(context,"My Car With Context"); } @Provides public String providerString(){ return "My New New Car"; }// @Provides// public Context providerContext(){// return this.context;// }}
这里我们把providerContext注释掉和构造函数注释掉,不提供context(由AppModule提供)
修改MainComponent:
@Singleton@Component(dependencies = {AppComponent.class},modules = {CarModule.class,BusModule.class})public interface MainComponent { void injectPerson(Person person); void injectMain(MainActivity activity);}
这里我们在@Component注解添加dependencies
也就是MainComponent 依赖AppComponent,所以可以通过 AppComponent中的 providesContext() 方法获取到Context对象。
修改MainActivity:
public class MainActivity extends AppCompatActivity { public final static String TAG="Main"; @CarWithContext @Inject Car car1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AppComponent appComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); DaggerMainComponent.builder().appComponent(appComponent).carModule(new CarModule()).build().injectMain(this); Log.w(TAG,car1.toString()); }}
我们发现实例Car的context被正常初始化。
阅读全文
0 0
- Android Dagger2入门详解(六)
- Android Dagger2入门详解(一)
- Android Dagger2入门详解(二)
- Android Dagger2入门详解(三)
- Android Dagger2入门详解(四)
- Android Dagger2入门详解(五)
- Dagger2 入门详解(一)
- dagger2使用入门详解(一)
- Dagger2入门详解
- [Android] Dagger2 入门 1
- [Android] Dagger2 入门 2
- Android开发Dagger2入门
- Android Dagger2简单入门
- Android Dagger2(一) Dagger使用详解
- Android:dagger2详解 2
- Android之Dagger2详解一
- Android常用开源工具(1)-Dagger2入门
- Android常用开源工具(1)-Dagger2入门
- 【总结】PHP常见面试题汇总(二)
- Arrays.asList()方法的使用
- uLua 热更新 增加Manager管理类时报错问题解决
- 《OC基础教程》读书笔记6-NSString基础方法整理
- linux系统挂载与取消挂载
- Android Dagger2入门详解(六)
- HDU
- RecyclerView 添加Header
- 【leetcode】第73题 Set Matrix Zeroes 题目+解析+JAVA代码
- 算法学习笔记4-动态规划-背包问题
- linux下更改mysql密码
- jsp 输出杨辉三角
- 【总结】PHP常见面试题汇总(三)
- TensorBoard使用