tôi có các module đơn giản sau đây:Ngữ cảnh không thể được cung cấp mà không có phương thức @ Provides-annotated, nhưng nó là gì?
@Module
public class ApplicationModule {
private CustomApplication customApplication;
public ApplicationModule(CustomApplication customApplication) {
this.customApplication = customApplication;
}
@Provides @Singleton CustomApplication provideCustomApplication() {
return this.customApplication;
}
@Provides @Singleton @ForApplication Context provideApplicationContext() {
return this.customApplication;
}
}
Và các thành phần đơn giản tương ứng:
@Singleton
@Component(
modules = ApplicationModule.class
)
public interface ApplicationComponent {
CustomApplication getCustomApplication();
Context getApplicationContext();
}
Và tôi là tạo ra các thành phần ở đây:
public class CustomApplication extends Application {
...
private ApplicationComponent component;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
Nó ném lỗi này tại thời gian biên dịch: Error:(22, 13) error: android.content.Context cannot be provided without an @Provides-annotated method
, nhưng như bạn có thể thấy nó được chú thích với @Provides
.
Thật kỳ lạ vì sự cố sẽ biến mất khi tôi gỡ chú thích vòng loại.
Chỉ trong trường hợp, đây là @ForApplication
vòng loại của tôi:
@Qualifier @Retention(RUNTIME)
public @interface ForApplication {
}
này thực chất là một cuốn sách giáo khoa Dagger2 ví dụ. Tôi đang làm gì sai?
Cùng một vấn đề ở đây. Tôi đã phải thêm '@ ForApplication' vào hàm tạo của mình:' @Inject MyThing (ngữ cảnh ngữ cảnh @ForApplication) {this.context = context; } ' – anon
Điều đó không có ý nghĩa. Bạn đang thực sự gọi 'getApplicationContext()' từ đâu? –
Bạn có thể xây dựng những gì chính xác không có ý nghĩa? Tôi không gọi phương thức đó, đó chỉ là một tuyên bố cho thành phần Dagger2. Tôi chỉ nói rằng chú thích bị thiếu trong phần khai báo 'Ngữ cảnh' trong phạm vi đó. Đó là lý do tại sao tôi nhận được lỗi, vì mô-đun của tôi đã chỉ định rằng ngữ cảnh được cung cấp là '@ ForApplication' và thành phần của tôi không. – Eddnav