I'm trying to use Play/Guice dependency injection with an interface:
public interface IService {
Result handleRequest();
}
public Service implements IService {
@Override
public Result handleRequest() {
...
return result;
}
}
public class Controller {
private final IService service;
@Inject
public Controller(IService service) {
this.service = service;
}
}
I get:
play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:
1.) No implementation for IService was bound.
If I change the controller class to not use the interface it works fine:
public class Controller {
private final Service service;
@Inject
public Controller(Service service) {
this.service = service;
}
}
How do I make it work with the interface so it finds the concrete Service class?
You can use guice annotation @ImplementedBy
like this:
import com.google.inject.ImplementedBy;
@ImplementedBy(Service.class)
public interface IService {
Result handleRequest();
}
Or u can use modules like this:
import com.google.inject.AbstractModule;
public class ServiceModule extends AbstractModule {
protected void configure() {
bind(IService.class).to(Service.class);
}
}
And then register them in application.conf play.modules.enabled += "modules.ServiceModule"