您无需在一个模块中显式地进行任何注入(字段或构造函数)。只需使用
addsTo和即可
includes。
includes允许将模块添加到另一个模块并使用它们提供的所有内容。例:
@Module()public class ModuleA { @Provides @Named("ValueA") String providevalueA() { return "This is ValueA"; }}@Module( includes = ModuleA.class)public class ModuleB { // ValueA comes from ModuleA @Provides @Named("ValueB") String providevalueB(@Named("ValueA") String valueA) { return valueA + " and ValueB"; }}
addsTo与一起使用
ObjectGraph.plus(Object...modules)。当图形已经创建并包含一些模块时(例如在Application类中),您可以使用创建新图形(例如在Activity中)
plus。例:
@Module()public class ApplicationModule { @Provides @Named("ValueA") String providevalueA() { return "This is ValueA"; }}@Module( addsTo = ApplicationModule.class)public class ActivityModule { // ValueA comes from ApplicationModule @Provides @Named("ValueB") String providevalueB(@Named("ValueA") String valueA) { return valueA + " and ValueB"; }}public class DemoApplication extends Application { private ObjectGraph graph; @Override public void onCreate() { super.onCreate(); graph = ObjectGraph.create(getModules().toArray()); } protected List<Object> getModules() { return Arrays.asList( new ApplicationModule() ); } public void inject(Object object) { graph.inject(object); } public ObjectGraph getObjectGraph() { return graph; }}public class DemoActivity extends Activity { private ObjectGraph activityGraph; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create the activity graph by .plus-ing our modules onto the application graph. DemoApplication application = (DemoApplication) getApplication(); activityGraph = application.getApplicationGraph().plus(new ActivityModule()); // Inject ourselves so subclasses will have dependencies fulfilled when this method returns. activityGraph.inject(this); } @Override protected void onDestroy() { // Eagerly clear the reference to the activity graph to allow it to be garbage collected as // soon as possible. activityGraph = null; super.onDestroy(); }}
您也可以检查此示例以创建图形范围。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)