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

我的模块:

@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”。 我在这里读到了关于这个问题及其说法的答案

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

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

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

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

所以Dagger确切地知道DefaultTcpManager.class