google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.45k stars 2.02k forks source link

error: @Provides methods may not override another method. #1374

Closed theapache64 closed 5 years ago

theapache64 commented 5 years ago

I want to use @Provides in-conjunction with @Override. but dagger says error: @Provides methods may not override another method.. So I wrote below fix

@Override
protected X getX() {
    return new X();
}

@Provides
X provideX() {
    return getX();
}

Is this a good approach ?

ronshapiro commented 5 years ago

We don't recommend it. It makes it much harder to understand what your Dagger graph is doing. Usually there's a better approach to allow you to have the same underlying effect. What are you trying to achieve?

One common solution is to have two different components that differ in the module that you're looking to "replace".

theapache64 commented 5 years ago

Yeah. I didn't like the approach too.

Actually, I wanted to create a base module that'll be extended by other modules. This module will be containing objects needed for the child modules. As @Provides cannot be used without @Module, I tried above method to return the instance of object needed in the base module.

As am new in Dagger (1 day), I wasn't too much aware/concerned about the @Module annotation and it's properties, but later today, I tried the includes property of @Module, and I could achieve what I was trying.

but now am facing another problem.

I've two modules. Let's say A and B. A has @Singleton providers and B has providers that are not singleton. I want to combine these modules in one component. but as we can't use un-scoped providers with scoped one, I tried the @Subcomponent method (https://stackoverflow.com/a/40923334/4370279). Now the problem is

error: [Dagger/SubcomponentFactoryMethodMissingModule] xComponent requires modules which have no visible default constructors. Add the following modules as parameters to this method: BaseActivityModule

theapache64 commented 5 years ago

Closing the issue , as I have learned the approach i've tried was an anti-pattern.

saurabhkpatel commented 5 years ago

@theapache64 how did you solve this problem? do you have any sample project which you could share?

theapache64 commented 5 years ago

Instead using Java inheritance, I've implemented the inheritance using module dependency. See here

pinkasey commented 4 years ago

I got here by googling the error message (of course). So this issue is important, even while closed.

I'll add my 2 cents: here's an explanation of a common use case that would naturally lead to inheritance of Modules, and the recommended way to implement it: https://dagger.dev/testing.html

hqzxzwb commented 3 months ago

Instead using Java inheritance, I've implemented the inheritance using module dependency. See here

But how do you achieve overriding with this?