Why is the dagger not interrupted at compile time when the class in the injection sentence cannot be entered?

I have this class:

public class ClassWithoutInject { } 

... and this module ...

 @Module( injects={ ClassWithoutInject.class }) public class SimpleModule { } 

Am I mistaken in thinking that this should give rise to a compile-time error? At runtime, I get:

  Unable to create binding for com.example.ClassWithoutInject required by class com.example.SimpleModule 

(Since the class does not have a @ Inject-annotated constructor). But shouldn't the dagger know what the compilation time is?

+6
source share
1 answer

Where do you actually enter ClassWithoutInjects ?

injects in a module refers to classes that will query the dependencies provided by that module.

So, in this case, Dagger expects ClassWithoutInjects request ClassWithoutInjects dependencies, with the dependencies provided by this module (which is currently empty).

If you want to provide ClassWithoutInjects as a dependency, and not as a dependency consumer (which is what it is configured like in a module), either add @Inject to the constructor, or add an explicit provider method in the module.

 @Module public class SimpleModule { @Provides ClassWithoutInjects provideClassWithoutInjects() { return new ClassWithoutInjects(); } } 

If ClassWithoutInjects is a dependency consumer.

 @Module(injects = ClassWithoutInjects.class) public class SimpleModule { // Any dependencies can be provided here // Not how ClassWithoutInjects is not a dependency, you can inject dependencies from // this module into it (and get compile time verification for those, but you can't // provide ClassWithoutInjects in this configuration } public class ClassWithoutInject { // Inject dependencies here } 
0
source

Source: https://habr.com/ru/post/955154/


All Articles