如果没有@ Provide-或@ Produces-annotated方法,则无法提供Dagger2

时间:2017-03-13 00:36:15

标签: java android dagger-2

所以我正在使用mvp模式开发应用程序,并且我在使用Dagger2时遇到问题

我为我的演示者创建了一个名为HelloPresenter的界面。

然后我为该接口创建了一个名为HelloPresenterImpl

的实现

我的HelloPresenter

public interface HelloPresenter {

    public void sayHello();

}

我的HelloPresenterImpl

public class HelloPresenterImpl implements HelloPresenter {

    StoryView storyView;

    @Inject
    public HelloPresenterImpl(StoryView storyView) {
        this.storyView = storyView;
    }

    @Override
    public void sayHello() {
        Log.d(TAG, "hello there");
    }

}

我的组件

@UserScope
@Component(dependencies = NetComponent.class, modules = RetrofitModule.class)
public interface StoryComponent {
    void inject(MainActivity activity);
    void inject(HelloPresenter helloPresenter);
}

我的模块

@Module
public class HelloModule {

    @Provides
    public HelloPresenter providesHelloPresenter(final HelloPresenterImpl presenter){
        return presenter;
    }

}

我的BaseApplication

public class BaseApplication extends Application {

    private NetComponent mNetComponent;
    private StoryComponent mStoryComponent;

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

        mNetComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .netModule(new NetModule())
                .build();

        mStoryComponent = DaggerStoryComponent.builder()
                .netComponent(mNetComponent)
                .retrofitModule(new RetrofitModule())
                .storyModule(new StoryModule())
                .build();

    }

    public NetComponent getNetComponent() {
        return mNetComponent;
    }

    public StoryComponent getStoryComponent() {
        return mStoryComponent;
    }

现在,当我尝试将其注入我的MainActivity时,它会抛出一个错误

  

错误:(18,10)错误:com.exampleapp.Hello.presenter.HelloPresenter   如果没有@ Provide-或@ Produces-annotated,则无法提供   方法。 com.exampleapp.Hello.presenter.HelloPresenter注入   com.exampleapp.Hello.MainActivity.HelloPresenter   com.exampleapp.Hello.MainActivity注入   com.exampleapp.di.components.HelloComponent.inject(活性)

public class MainActivity extends AppCompatActivity {

    @Inject
    SharedPreferences mSharedPreferences;

    @Inject
    StoryInterface storyInterface;

    @Inject 
    HelloPresenter helloPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((BaseApplication) getApplication()).getStoryComponent().inject(this);

        helloPresenter.sayHello();  // This throws an Error

    }

请有人指出我正确的方向吗?感谢

1 个答案:

答案 0 :(得分:7)

如果没有看到整个项目,我的猜测是Dagger无法计算如何创建HelloPresenterImpl实例,因为您没有提供StoryView。我认为你需要:

@Provides
public StoryView providesStoryView() {
    return new StoryView();
}