I am trying to create a Dagger in Java code (not Android) for an Interface which has two or more implementations. I was able to do it successfully with CDI using javax libraries but I want to use Dagger this time around as per my project need. I am not able to call right implementation or event resolve the dependency during compilation. I am getting error with either multiple binding or missing binding.
I am new to Dagger2 and trying to figure this out.
So I started creating an interface first:
public interface Engine {
public startEngine();
}
Engine has two implementations Petrol and Diesel
public class PetrolEngine implements Engine {
@Inject
public PetrolEngine(){}
@Override
public startEngine() {
System.out.println("Petrol Engine Start");
}
}
public class DieselEngine implements Engine {
@Inject
public DieselEngine(){}
@Override
public startEngine() {
System.out.println("Diesel Engine Start");
}
}
Module created as
@Module
public class EngineModule {
@Provides
@IntoMap
@StringKey("Petrol")
public Engine providesEngine(PetrolEngine petrolEngine){
return petrolEngine;
}
@Provides
@IntoMap
@StringKey("Diesel")
public Engine providesEngine(DieselEngine dieselEngine){
return dieselEngine;
}
}
Component
@Component(module = EngineModule.class)
public interface EngineComponent {
EngineService providesEngineService();
}
Finally the Service that will call either Petrol or Diesel
public call EngineService {
private Engine engine;
@Inject
public EngineService(Engine engine) {
this.engine = engine;
}
public void getEngineInstance() {
//Some code to get the Petrol/Diesel Engine Instance
}
}