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

내가 필요한 것. 감사 –

관련 문제