gpt4 book ai didi

java - 当无法注入(inject) injects 子句中的类时,为什么 dagger 在编译时不会失败?

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:46 25 4
gpt4 key购买 nike

我有这门课:

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 不应该在编译时知道吗?

最佳答案

您实际上在哪里注入(inject) ClassWithoutInjects

模块上的 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
}

关于java - 当无法注入(inject) injects 子句中的类时,为什么 dagger 在编译时不会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com