Dagger2:是否可以从依赖组件中使用inject()和@Inject注入?

时间:2016-04-07 16:06:03

标签: android dependency-injection dagger-2

我设法使用注入在依赖的Component接口中声明 ChildObject childObject()方法,并在使用者类中使用 myParentComponent.childObject()

我尝试在使用者类中使用标准方式 void inject(Main mainActivity)声明和@Inject,但它不起作用:

  

错误:(7,10)错误:如果没有@Inject构造函数或@ Provide-或> @ Produces-annotated方法,则无法提供com.jgl.dagger2dependentcomponent.ChildModule.ChildObject>。   com.jgl.dagger2dependentcomponent.MainActivity.childObject   [注入字段类型:com.jgl.dagger2dependentcomponent.ChildModule.ChildObject childObject]

MainActivity

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Inject
    ChildModule.ChildObject childObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ParentComponent parentComponent = DaggerParentComponent.builder().parentModule(new ParentModule()).build();
        ChildComponent childComponent = DaggerChildComponent.builder().parentComponent(parentComponent).childModule(new ChildModule()).build();
        childComponent.inject(this);
        Log.d(TAG, "childObject is null : " + (childObject == null ? "true" : "false"));
    }
}

父组件

package com.jgl.dagger2dependentcomponent;

import dagger.Component;

@Component(modules=ParentModule.class)
public interface ParentComponent {
    void inject(MainActivity mainActivity);
    ParentModule.ParentObject parentObject();
}

ParentModule

package com.jgl.dagger2dependentcomponent;

import dagger.Module;
import dagger.Provides;

@Module
public class ParentModule {

    @Provides
    ParentObject providesParentObject(){
        return new ParentObject();
    }

    public static class ParentObject{}
}

ChildComponent

package com.jgl.dagger2dependentcomponent;

import dagger.Component;

@Component(dependencies = ParentComponent.class, modules = ChildModule.class)
public interface ChildComponent {
    void inject(MainActivity mainActivity);
}

ChildModule

package com.jgl.dagger2dependentcomponent;

import dagger.Module;
import dagger.Provides;

@Module
public class ChildModule {

    @Provides
    ChildObject providesChildObject(ParentModule.ParentObject parentObject){
        return new ChildObject(parentObject);
    }

    public static class ChildObject{
        private ParentModule.ParentObject parentObject;

        public ChildObject(ParentModule.ParentObject parentObject) {
            this.parentObject = parentObject;
        }
    }
}

0 个答案:

没有答案