Play框架依赖项注入无法正常工作

时间:2019-04-16 16:48:04

标签: java dependency-injection playframework

我从这里尝试过依赖注入示例 https://dzone.com/articles/guicing-play-framework

下面是我的代码 控制器:

public class TestController extends Controller{
  @Inject
  private Testing test;

  public Result result() {
    test.tt();
    return ok();
  } 
}

服务接口代码:

public interface Testing {
  public String tt();
}

ServiceImpl代码:

public class Testingimpl implements Testing{
  @Override
  public String tt() {
    return "test";
  }
}

我收到此错误

  

CreationException:无法创建注入器

如果我这样做,这行得通。

public class TestController extends Controller{
  @Inject
  private TestingImpl test;

  public Result result() {
    test.tt();
    return ok();
  } 
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您忘记了将接口绑定到实现。如果您有一种实现,请更改您的界面,例如:

import com.google.inject.ImplementedBy;

@ImplementedBy(Testingimpl.class)
public interface Testing {
    public String tt();
}

对于更复杂的解决方案,您可以使用程序绑定:https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection#Programmatic-bindings