我的模块:
@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/