为什么在编译时不能注入injects子句中的类时dagger不会失败?

Jef*_*ght 6 java module runtime compile-time dagger

我有这门课:

public class ClassWithoutInject {

}
Run Code Online (Sandbox Code Playgroud)

......和这个模块......

@Module(
        injects={
                ClassWithoutInject.class 
        })
public class SimpleModule {
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该产生编译时错误我错了吗?在运行时,我得到:

  Unable to create binding for com.example.ClassWithoutInject required by class com.example.SimpleModule
Run Code Online (Sandbox Code Playgroud)

(因为该类没有@Inject-annotated构造函数).但是不应该在编译时匕首知道吗?

f2p*_*eek 0

你实际上在哪里注射ClassWithoutInjects

模块injects上的 指的是将从该模块提供的依赖项请求依赖项的类。

因此,在这种情况下,Dagger 期望ClassWithoutInjects从 ObjectGraph 请求依赖项,并由该模块提供依赖项(当前为空)。

如果您想作为依赖项提供ClassWithoutInjects,而不是作为依赖项的使用者(这是在模块中设置的),请@Inject在其构造函数上添加 ,或在模块中添加显式提供程序方法。

@Module
public class SimpleModule {
  @Provides ClassWithoutInjects provideClassWithoutInjects() {
    return new ClassWithoutInjects();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果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
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,我的问题不是“为什么这段代码不起作用”,而是“为什么它直到运行时才失败” (2认同)