Dagger2

dependencies:

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

被依赖者

@Singleton @Component(modules = { ActivityModel.class, TagModel.class })public interface ActivityComponent {  StringgetMyString();  LocalUsergetLoca();  ApiUsergetABC();  UtilsgetUtils();}

moudle

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

依赖者

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

application中使用

public class MyApplicationextends Application {private ActivityComponentActivityComponent;  @Override public void onCreate() {super.onCreate();    ActivityComponent = DaggerActivityComponent.builder()        .activityModel(new ActivityModel("oko"))        .tagModel(new TagModel())        .build();  }public ActivityComponentgetModel() {return ActivityComponent;  }}

activity中使用  DaggerOneComponent.builder().activityComponent(((MyApplication)getApplication()).getModel()).build().inject(this);

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

通过构造方式注解的例子

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容