0x3333 0x3333 - 2 months ago 27
Java Question

Change a binding to a proxy

I create a proxy class using a APT(Annotation Processor) to do some instrumentation in the original class.

I want to change a binding in Dagger 2 with this proxy instead of the default implementation when the implementation class is annotated with @MyCustomAnnotation.

Implementation(By user):

@MyCustomAnnotation
public class MyServiceImpl implements MyService {
// Implementation
}


Original Module:

@Module
public class AppModule {
@Provides
@Singleton
MyService providesService() {
return new MyServiceImpl();
}
}


Final module replacing the implementation:

@Module
public class AppModule {
@Provides
@Singleton
MyService providesService() {
return new MyServiceImplProxy();
}
}


I need something transparent from a user perspective.

What do you guys suggest?

Answer

Well, I ended up using @Binds and doing a double bind.

Changed the user module to a simple @Binds:

@Module(includes = { OverrideModule.class })
public abstract class AppModule {
  @Binds
  @Singleton
  abstract MyService providesMyService(MyServiceImpl impl);
}

And created a override module:

@Module
public abstract class OverrideModule {
  @Binds
 abstract MyServiceImpl providesMyServiceImpl(MyServiceImplProxy impl);
}
Comments