dagger2踩坑

本文详细介绍了Dagger依赖注入框架的使用方法,包括如何通过注解实现组件间的依赖关系,如何在不同层级如Application和Activity中正确配置和使用依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dependencies:

一个component可以通过此注解依赖另外一个component,但是所依赖的component中必须要提供所要使用的modules中provide所注解的方法,并且返回值相同,如果其中有named注解的方法 这里的返回值为void,如果依赖的component有@signton标注,依赖者必须自定义一个signton标注并放在上面,例如:


被依赖者

@Singleton @Component(modules = { ActivityModel.class, TagModel.class })
public interface ActivityComponent {
  String getMyString();

  LocalUser getLoca();

  ApiUser getABC();

  Utils getUtils();
}


moudle

@Module public class TagModel {
   @Provides public Utils getUtils() {
    return new Utils();
  }
}

依赖者

@Single
@Component(dependencies = ActivityComponent.class) public interface OneComponent {
  void inject(MainActivity mainActivity);
}

application中使用

public class MyApplication extends Application {
  private ActivityComponent ActivityComponent;

  @Override public void onCreate() {
    super.onCreate();

    ActivityComponent = DaggerActivityComponent.builder()
        .activityModel(new ActivityModel("oko"))
        .tagModel(new TagModel())
        .build();
  }

  public ActivityComponent getModel() {
    return ActivityComponent;
  }
}
activity中使用  DaggerOneComponent.builder().activityComponent(((MyApplication)getApplication()).getModel()).build().inject(this);


使用构造方法进行注解的时候一定要注意  注解的地方要在当前使用的DaggerBeanComponent.create().inject(this)的activity或者他的子类中使用,不能在父类中使用



通过构造方式注解的例子










由这三步可以知道  通过构造方式注解根本就与module没得关系  在你需要的对象构造方法中加上@inject    在你需要对象的类中@inject类  中间只需要写一个component来把这个需要对象的类连接起来就行了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值