2016-10-19 4 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

私が必要としたもの。ありがとう –

関連する問題