【问题标题】:Play and Guice Dependency Injection with Interface带接口的 Play 和 Guice 依赖注入
【发布时间】:2019-02-19 21:44:09
【问题描述】:

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

如何使它与接口一起工作,以便找到具体的服务类?

【问题讨论】:

    标签: dependency-injection playframework guice


    【解决方案1】:

    你可以像这样使用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"

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2021-02-22
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多