【问题标题】:Dagger 2 - injecting multiple objects of same type using @Named not workingDagger 2 - 使用@Named 注入多个相同类型的对象不起作用
【发布时间】:2017-03-01 13:38:11
【问题描述】:

我的模块:

@Module
public class TcpManagerModule {
    private ITcpConnection eventsTcpConnection;
    private ITcpConnection commandsTcpConnection;

    public TcpManagerModule(Context context) {
        eventsTcpConnection = new EventsTcpConnection(context);
        commandsTcpConnection = new CommandsTcpConnection(context);
    }

    @Provides
    @Named("events")
    public ITcpConnection provideEventsTcpConnection() {
        return eventsTcpConnection;
    }

    @Provides
    @Named("commands")
    public ITcpConnection provideCommandsTcpConnection() {
        return commandsTcpConnection;
    }
}

组件:

@Component(modules = TcpManagerModule.class)
public interface TcpManagerComponent {
    void inject(ITcpManager tcpManager);
}

发生注入的类:

public class DefaultTcpManager implements ITcpManager {
    private TcpManagerComponent tcpComponent;

    @Inject @Named("events") ITcpConnection eventsTcpConnection;

    @Inject @Named("commands") ITcpConnection commandsTcpConnection;

    public DefaultTcpManager(Context context){
        tcpComponent = DaggerTcpManagerComponent.builder().tcpManagerModule(new TcpManagerModule(context)).build();
        tcpComponent.inject(this);
    }

    @Override
    public void startEventsConnection() {
        eventsTcpConnection.startListener();
        eventsTcpConnection.connect();
    }
}

当我调用startEventsConnection 时,我得到NullPointerException - 这意味着注入没有填充字段。

我完全按照文档中的示例进行操作,有什么问题?

注意: builder

tcpComponent = DaggerTcpManagerComponent.builder().tcpManagerModule(new TcpManagerModule(context)).build();

我有一条警告说“tcpManagerModule 已弃用”。我阅读了关于这个问题的答案here,以及它的说法

可以肯定地说,您可以忽略弃用。它旨在通知您未使用的方法和模块。只要您在子图中的某处实际需要/使用 Application ,就会需要该模块,并且弃用警告将消失。

那么,我不需要/使用这些实例吗?这里有什么问题?

【问题讨论】:

    标签: java android dependency-injection dagger-2 dagger


    【解决方案1】:

    您可以尝试更改您的 Component 定义注入的特定类:

    @Component(modules = TcpManagerModule.class)
    public interface TcpManagerComponent {
        void inject(DefaultTcpManager tcpManager);
    }
    

    这样 Dagger 就可以准确地知道DefaultTcpManager.class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2017-02-17
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多