Dagger 2-使用Provider <t>进行依赖项注入

时间:2019-03-12 20:24:55

标签: java dependency-injection dagger-2 dagger

我有一个具有一个抽象成员字段的类。

public class Editor implements PropertyEditor {

    @Inject
    AbstractEditor editor;

    @Inject
    public Editor() {
    }

    (...)
}

使用匕首和提供程序接口,我想创建两个不同的对象并注入不同的AbstractEditor实现,如下所示:

@Singleton
public class EditorFactory {

    @Inject 
    Provider<Editor> numericEditorProvider;

    @Inject 
    Provider<Editor> textEditorProvider;

    (...)

    static WidgetCreator INTEGER = new WidgetCreator(EditorType.INTEGER) {

        @Override
        public PropertyEditor create(EditorFactory factory) {
            return factory.numericEditorProvider.get();
        }
    };

    static WidgetCreator STRING = new WidgetCreator(EditorType.STRING) {

        @Override
        public PropertyEditor create(EditorFactory factory) {
            return factory.textEditorProvider.get();
        }
    };
}

是否可以将AbstractEditor的具体实例传递给每个编辑器? INTEGER应该提供IntegerEditor,STRING应该私有StringEditor。

IntegerEditor extends AbstractEditor

StringEditor extends AbstractEditor

0 个答案:

没有答案