Dagger 2 - 使用@Named 注入多个相同类型的对象不起作用

Dagger 2 - injecting multiple objects of same type using @Named not working

我的模块:

@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);
}

class 发生注入的位置:

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 is deprecated"。我阅读了关于这个问题的答案,它的说法

It is safe to say that you can just ignore the deprecation. It is intended to notify you of unused methods and modules. As soon as you actually require / use Application somewhere in your subgraph the module is going to be needed, and the deprecation warning will go away.

那么,我不是requiring/using个体吗?这里有什么问题?

您可以尝试更改 Component 定义用于注入的特定 class:

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

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