美文网首页
Dagger 子组件(dependencies)

Dagger 子组件(dependencies)

作者: coke613 | 来源:发表于2023-07-17 11:25 被阅读0次
    在Dagger 中,可以创建一个组件的层次结构,其中子组件可以依赖父组件.

    通过dependencies 参数来实现组件层次结构.

    dependencies参数是@ Component 注解的参数.

    
    // ApplicationCommponent 作为父组件
    
    @Singleton
    @Component(modules = NetWorkModule.class)
    public interface ApplicationCommponent {
    
    //    void injectUser(TextDaggerActivity mainActivity);
    
        Retrofit getRetrofit();
    }
    
    @Module
    public class NetWorkModule {
        @Provides
        @Singleton
        public Retrofit provideRetrofit(){
            return new Retrofit.Builder()
                    .baseUrl("https://www.google.com")
                    .build();
        }
        @Singleton  
        @Provides
        public Api providesApi(Retrofit retrofit){
            return retrofit.create(Api.class);
        }
    
    }
    

    创建子组件, 通过dependencies 指向了ApplicationCommponent.class

    @UserScoped
    @Component(modules = UserModule.class,dependencies = ApplicationCommponent.class)
    public interface UserCommponent {
        void inject(TextDaggerActivity activity);
    }
    

    UserModule.java

    @Module
    public class UserModule {
       @UserScoped
       @Provides
       public User provideUser(){
          return new User();
       }
    }
    
    

    User.java

    public class User {
       public User(){
       }
    }
    

    自定义注解接口,用于区分父组件作用域.

    @Scope
    @Documented
    @Retention(RUNTIME)
    public @interface UserScoped {
    }
    
    

    获取子组件实例

    public class TextDaggerActivity extends AppCompatActivity {
    
       @Inject
       Retrofit retrofit1;
    
       @Inject
       User user;
    
       @Override
       protected void onCreate(@Nullable Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
    
          DaggerUserCommponent.builder().applicationCommponent(App.applicationCommponent).build().inject(this);
    
          Log.e("retrofit1----","address: "+retrofit1);
          Log.e("user----","address: "+user);
       }
    }
    
    

    打印结果

    E/retrofit1----: address: retrofit2.Retrofit@5707fc6
    E/user----: address: com.zh.hellokotlin.dagger.bean.User@f8eb87
    

    使用dependencie需要注意的点

    • Component容器中功能对象只能在一个 容器中引用声明. 不能重复.在UserCommponent类中,inject 参数是TextDaggerActivity. 而'TextDaggerActivity'就不可以在其他Component 容器中使用.

    • 作用域. 子组件和父组件作用域是不一样的.需要区分开.

    • 子组件不能直接访问父组件的Module, 需要父组件显示的声明.
      在上述例子中,父组件Module, 提供了获取Retrofit,Api. 实例. 需要在父组件容器中,动态的声明,如下. 这样子组件就可以拿到父组件中的实例.


    • 拿到子容器实例不同



    获取子容器实例需要使用 DaggerXXX.builder().父组件容器(父组件容器实例).build().函数();

    相关文章

      网友评论

          本文标题:Dagger 子组件(dependencies)

          本文链接:https://www.haomeiwen.com/subject/nmhgudtx.html