Java 当injects子句中的类不能被注入时,为什么dagger在编译时不会失败?
我有这门课:Java 当injects子句中的类不能被注入时,为什么dagger在编译时不会失败?,java,module,runtime,compile-time,dagger,Java,Module,Runtime,Compile Time,Dagger,我有这门课: public class ClassWithoutInject { } 。。。这个模块 @Module( injects={ ClassWithoutInject.class }) public class SimpleModule { } 我认为这会产生编译时错误,这是错误的吗?在运行时,我得到: Unable to create binding for com.example.ClassWithoutI
public class ClassWithoutInject {
}
。。。这个模块
@Module(
injects={
ClassWithoutInject.class
})
public class SimpleModule {
}
我认为这会产生编译时错误,这是错误的吗?在运行时,我得到:
Unable to create binding for com.example.ClassWithoutInject required by class com.example.SimpleModule
(因为该类没有@Inject注释的构造函数)。但dagger难道不应该在编译时知道吗?您实际上在哪里使用outjects注入
类
模块上的injects
引用将从该模块提供的请求依赖项的类
因此,在本例中,Dagger希望ClassWithoutInjects
从ObjectGraph请求依赖项,依赖项由该模块提供(当前为空)
如果您想将ClassWithoutInjects
作为依赖项提供,而不是作为依赖项的使用者(这是在模块中设置的),请在其构造函数中添加@Inject
,或者在模块中添加显式提供程序方法
@Module
public class SimpleModule {
@Provides ClassWithoutInjects provideClassWithoutInjects() {
return new ClassWithoutInjects();
}
}
如果ClassWithoutInjects
是依赖项的使用者
@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
}
你的类路径上有dagger编译器吗?是的。(若我并没有,我相信它会说一些关于无效模块的事情,你们确定代码生成已经运行了吗)。如果我给那个类添加一个@Inject注释的构造函数,一切都会好起来。哦,对了。v1.1+需要使用编译器。。。我以后得在本地试试。或者其他人可以在那之前提供帮助。虽然这是一个错误,但我是正确的吗?也就是说,你会期望代码在编译时失败?对我来说似乎应该是这样。是的,我的问题不是“为什么这段代码不工作”,而是“为什么它在运行时才失败”