dagger2 找不到符号

dagger2 cannot find symbol

我正在关注 TODO 应用程序的 Dagger2 示例,但遇到了 2 个错误。

错误 1:找不到符号 DaggerNetComponent。 (实际上在那里)
Error2: Sharedpreference cannot be provided without @provider-annotated method.(我认为这是错误1的结果)

这是我的长而简单的代码:
三个模块:

@Module
public class AppModule {
    private final Application mApplication;

    AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    Application provideApplication() {
        return mApplication;
    }
}

@Module
public class LoadingModule {
    public final LoadingContract.View mView;

    public LoadingModule(LoadingContract.View mView) {
        this.mView = mView;
    }

    @Provides
    LoadingContract.View provideLoadingContractView() {
        return mView;
    }
}

@Module
public class NetModule {

    @Provides @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }
}


还有两个分量:

@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
}

@FragmentScoped
@Component(dependencies = NetComponent.class, modules = LoadingModule.class)
public interface LoadingComponent {
    void inject(LoadingActivity loadingActivity);
}


我在 MyApplication 中得到 NetComponent:

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


和 LoadingActivity 中的 LoadingComponent:

DaggerLoadingComponent.builder()
                .netComponent(((MyApplication)getApplication()).getNetComponent())
                .loadingModule(new LoadingModule(loadingFragment))
                .build()
                .inject(this);


我唯一想要LoadingComponent注入的是LoadingPresenter
也在LoadingActivity

@Inject LoadingPresenter mLoadingActivityP; 


这就是 LoadingPresenter 的构造方式:

public class LoadingPresenter implements LoadingContract.Presenter {
    private SharedPreferences sharedPreferences;
    private LoadingContract.View loadingView;

    @Inject
    public LoadingPresenter(LoadingContract.View loadingView, SharedPreferences sharedPreferences) {
        this.loadingView = loadingView;
        this.sharedPreferences = sharedPreferences;
    }

    @Inject
    void setupListeners() {
        loadingView.setPresenter(this);
    }

    public boolean checkLoginStatus() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        return sharedPreferences.getBoolean("loginStatus", false);
    }

    @Override
    public void start() {
    }
}


我的程序结束。
困扰我好几天了。感谢您的帮助。

你把错误的因果关系倒过来了。 Dagger* 类 是注释处理器的最终输出。因为你的图表有错误,Dagger 处理器无法完成,所以输出丢失了。

第二个错误是说您正在从一个没有绑定它的组件中请求 SharedPreferences。因为您选择了组件依赖项而不是子组件,所以来自您的依赖项的所有绑定都不会被继承。为了让您的 LoadingComponent 使用来自 NetComponent 的绑定,它们必须在组件接口上公开。将 SharedPreferences sharedPreferences(); 添加到 NetComponent 或切换到子组件应该可以解决您的问题。

有关详细信息,请参阅 @Component docs and the page on subcomponents in the user's guide