Home >Java >javaTutorial >How to Fix Dagger 2's 'cannot be provided' Error?

How to Fix Dagger 2's 'cannot be provided' Error?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 16:02:14170browse

How to Fix Dagger 2's

Fixing Dagger 2 Error: "... cannot be provided [...]"

This error occurs when Dagger 2 cannot provide a dependency without an annotated constructor or a method annotated with @Provides. To resolve it:

1. Add an @Inject Constructor

Add an @Inject annotated constructor to the class that is not provided:

class MyDependency {
    @Inject
    MyDependency() { /**/ }
}

Dagger will then use this constructor to create the instance.

2. Create a @Provides Method in a Module

Alternatively, create a method annotated with @Provides in a module that returns the dependency:

@Module
class MyModule {
    @Provides
    MyDependency provideMyDependency() {
        return new MyDependency();
    }
}

Dagger will use this method to create and provide the dependency.

Additional Considerations

  • Ensure that the provided dependency is the same type as the requested dependency (i.e., not a superclass or interface).
  • Verify that the component provides the dependency (e.g., MyComponent.myDependency()).
  • If using interfaces, use @Binds to specify the implementation provided.

The above is the detailed content of How to Fix Dagger 2's 'cannot be provided' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn