对不起我的英语,现在我开始学习dagger2,我不明白为什么我有错误:
错误:(9,10)错误: test.dagger.dagger.modules.MainActivityPresenterModule不能 没有@Inject构造函数或@ Provide-或者提供 @ Produces-annotated方法。 注入test.dagger.dagger.modules.MainActivityPresenterModule test.dagger.view.activitys.MainActivity.mainActivityPresenterModule test.dagger.view.activitys.MainActivity注入 test.dagger.dagger.components.AppComponent.injectMainActivity(mainActivity)
应用
public class App extends Application {
private static AppComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerAppComponent.create();
}
public static AppComponent getComponent() {
return component;
}
}
AppComponent
@Component(modules = {MainActivityPresenterModule.class})
public interface AppComponent {
void injectMainActivity(MainActivity mainActivity);
}
MainActivityPresenterModule
@Module
public class MainActivityPresenterModule {
@Provides
MainActivityPresenter provideActivityPresenter(NetworkUtils networkUtils) {
return new MainActivityPresenter(networkUtils);
}
@Provides
NetworkUtils provideNetworkUtils(){
return new NetworkUtils();
}
}
NetworkUtils
public class NetworkUtils {
public boolean isConnection() {
return true;
}
}
MainActivityPresenter
public class MainActivityPresenter {
NetworkUtils networkUtils;
public MainActivityPresenter(NetworkUtils networkUtils) {
this.networkUtils = networkUtils;
}
public void getUser(){
if(networkUtils.isConnection()) {
Log.e("getUser", "getUser");
} else {
Log.e("no internet", "no internet connection");
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
@Inject
MainActivityPresenterModule mainActivityPresenterModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
App.getComponent().injectMainActivity(MainActivity.this);
}
}
答案 0 :(得分:2)
您只能注入用@Module
注释的类中提供的内容(只有该模块中用@Provides
注释的方法)。所以,你可以做@Inject MainActivityPresenter presenter
,例如,不要尝试注入整个模块,就像你试图做的那样。模块应该在Dagger初始化时注册,就像这样(在App#onCreate中)
component = DaggerAppComponent.builder()
.mainActivityPresenterModule(MainActivityPresenterModule())
.build()
在MainActivity中,您只需调用inject即可注入模块中定义的@Inject MainActivityPresenter presenter
或任何其他注入,如下所示:
@Inject MainActivityPresenter presenter
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
(application as App).component.inject(this)
// after #inject(this) above you can start using your injections:
presenter.getUser()
}
抱歉,我在Kotlin编写了代码片段,因为用这种方式编写代码片段要少得多,希望你能够了解它在Java中的外观。