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

标签 java android dependency-injection dagger-2 dagger

我的模块:

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

发生注入(inject)的类:

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 - 意味着注入(inject)未填充字段。

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

注意:构建器

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

我收到一条警告,提示“tcpManagerModule 已弃用”。我读了答案here关于这个问题及其说法

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.

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

最佳答案

您可以尝试更改定义用于注入(inject)的特定类的Component:

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

以便 Dagger 准确了解 DefaultTcpManager.class

关于java - Dagger 2 - 使用 @Named 注入(inject)多个相同类型的对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139428/

相关文章:

java - 如何将 swagger 与 jersey + spring-boot 整合

java - Spring云合约和webflux路由

c# - 使用 Xamarin (Android) 从某个位置请求 POI

android - 永远不会调用 OnInfoListener

java - Guice:使用属性绑定(bind)注解

java - 我不知道如何将树插入堆栈

java - 是否每个 "new"都会导致至少一次 Classloader.loadClass 调用

android - 定期检查以太网连接android

java - Spring:如何通过 XML 将属性值注入(inject)到 bean 中?

php - 如何使用依赖注入(inject)和接口(interface)创建连接类?