Play 和 Guice 接口依赖注入

Play and Guice Dependency Injection with Interface

我正在尝试通过接口使用 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.  

如果我将控制器 class 更改为不使用界面,它会正常工作:

public class Controller {
    private final Service service;

    @Inject
    public Controller(Service service) {
        this.service = service;
    }
}

如何让它与界面一起工作,以便它找到具体的服务 class?

您可以像这样使用 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.confplay.modules.enabled += "modules.ServiceModule"

中注册