Use Dagger modules without the “injects” directive

只愿长相守 提交于 2019-12-02 19:14:33

You want

@Module(library=true)

Here's what the docs say about library:

False if all the included bindings in this module are necessary to satisfy all of its injectable types. If a module is not a library module, it is eligible for additional static checking: tools can detect if included bindings are not necessary. If you provide bindings that are not used by this module's graph, then you must declare library = true.

(emphasis mine)


Declaring a module as a library does not alleviate the needs of Dagger to know about injection points. You still must declare a module in the object graph with the listed injects.

An extreme simplified version of your example would look like this:

repo/
 +- library/
 |   +- Foo.java
 |   `- FooModule.java
 |
 `- app/
     +- BarActivity.java
     `- BarModule.java

FooModule.java:

@Module(library = true)
public final class FooModule {
  @Provides @Singleton provideFoo() {
    return Foo();
  }
}

BarModule.java:

@Module(
  injects = BarActivity.class,
  includes = FooModule.class
)
public final class BarModule {
}

In BarActivity.java (or similar):

ObjectGraph og = ObjectGraph.create(new BarModule());
og.inject(this);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!