2016-10-19 35 views
2

我的模塊:匕首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 - 意味着注射沒有填充字段。

我完全按照它在Docs上的方式來跟蹤示例,這有什麼問題?

注:建設者

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

我有一個警告說 「tcpManagerModule已經過時」。我讀了關於這個問題的回答here,並且它的說法

可以肯定地說,你可以忽略棄用。它旨在通知您未使用的方法和模塊。只要您實際需要/使用您的子圖中某處的應用程序,該模塊將需要使用,並且棄用警告將消失。

所以,我不需要/使用實例嗎?這裏有什麼問題?

回答

2

你可以試着改變你的Component定義注入的具體類:

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

這樣匕首確切地知道關於DefaultTcpManager.class

+0

正是我所需要的。謝謝 –