Play framework dependency injection is not working

user3334226 :

I have tried dependency injection example from here https://dzone.com/articles/guicing-play-framework

Below is my code Controller:

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

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

Service Interface code:

public interface Testing {
  public String tt();
}

ServiceImpl code:

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

I am getting this error

CreationException: Unable to create injector

If I do this, this works.

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

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

How to resolve this?

Yevgen :

You forgot to bind interface to your implementation. If you have one implementation change your interface like:

import com.google.inject.ImplementedBy;

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

For more complex solution you can use programmatic bindings: https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection#Programmatic-bindings

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157898&siteId=1