我正在尝试使用接口播放Play / Guice依赖注入:
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;
}
}
我明白了:
play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:
1.) No implementation for IService was bound.
如果我改变控制器类不使用接口它工作正常:
public class Controller {
private final Service service;
@Inject
public Controller(Service service) {
this.service = service;
}
}
如何使它与界面一起工作,以便找到具体的Service类?
你可以像这样使用guice注释@ImplementedBy
:
import com.google.inject.ImplementedBy;
@ImplementedBy(Service.class)
public interface IService {
Result handleRequest();
}
或者你可以使用这样的模块:
import com.google.inject.AbstractModule;
public class ServiceModule extends AbstractModule {
protected void configure() {
bind(IService.class).to(Service.class);
}
}
然后在application.conf play.modules.enabled += "modules.ServiceModule"
中注册它们