6

我有这堂课:

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 注释的构造函数)。但是匕首不应该在编译时知道吗?

4

1 回答 1

0

Where are you actually injecting ClassWithoutInjects?

The injects on the Module refers to classes that will request dependencies from the provided by that module.

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

If you wanted to provide ClassWithoutInjects as a dependency, and not as consumer of the dependencies (which is what it is setup as in the module), either add the @Inject on it's constructor, or add an explicit provider method in the module.

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

If ClassWithoutInjects is a consumer of dependencies.

@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
}
于 2014-03-05T16:38:53.363 回答