Dagger 2 - 使用@Named无法正常注入多个相同类型的对象

时间:2016-10-19 18:55:37

标签: 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);
}
发生注射的

类:

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 - 意味着注射没有填充字段。

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

注意:构建器

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

我有一个警告说" tcpManagerModule已被弃用"。我阅读了有关此问题的答案here及其说法

  

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

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

1 个答案:

答案 0 :(得分:2)

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

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

所以Dagger确切地知道DefaultTcpManager.class

相关问题