如何使用java回调的依赖注入

时间:2016-09-19 18:01:15

标签: java android dependency-injection dagger

我正在开发Android应用,并希望将Dagger用作我的DI框架。但我不知道如何注入使用回调的依赖项。

例如,我想获取位置,我使用GoogleApiClient:

public class LocationProvider implements ILocationProvider,
                                     GoogleApiClient.ConnectionCallbacks,
                                     GoogleApiClient.OnConnectionFailedListener {
    private GoogleApiClient googleApiClient;
    private ILocationRequester requester;

    public LocationProvider(@NonNull Context context, @NonNull ILocationRequester requester) {
        this.requester = requester;

        googleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    }

    @Override
    public void beginGetLocation() {
        googleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        requester.locationFound(lastLocation);
    }

    @Override
    public void onConnectionSuspended(int i) {
        requester.locationFound(null);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        requester.locationFound(null);
    }
}

在这种情况下,我想使用Dagger注入GoogleApiClient实例,以便能够在我的测试中对其进行模拟,但是因为它依赖于这个类我无法做到。该场景对于使用回调的任何长时间运行操作都有效,即使我使用另一个类来实现回调。

有人知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

您需要为接口编写实现类,并将其称为“ILocationRequesterImpl”,然后编写一个方法来提供该impl的实例。例如在你的模块中:

  @Provides
public ILocationRequester provideLocationRequester() {
    ILocationRequesterImpl lr=new ILocationRequesterImpl();
    return lr;
}

另一种方法是在ILocationRequesterImpl类中使用构造函数注入,如下所示:

public class ILocationRequesterImpl implements ILocationRequester {
@Inject
public ILocationRequesterImpl() {
} ... ...

然后这次在你的模块中写下:

  @Provides
public ILocationRequester provideLocationRequester(ILocationRequesterImpl lr) {
    return lr;
}