injecting interface with multiple implementations in play framework

zee :

I want to inject java interface using @Inject annotation but since there are multiple implementations of this interface, I am not getting how play framework will resolve I am trying to find something like the qualifier annotation in spring but am unable to found something like this in play documentation. Please let me know how this can be achieved.

interface i1 {
    void m1() {}
}
class c1 implements i1{}
class c2 implements i1{}

class c {
    @Inject 
    i1 i; // which instance will be injected here how to resolve this conflict.
}
Andriy Kuba :

Play framework use Guice:

https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection https://github.com/google/guice/wiki/Motivation

You can achieve it in different ways. The simplest examples:

1. Binding annotations

If you need only one realization. https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection#Binding-annotations

import com.google.inject.ImplementedBy;

@ImplementedBy(c1.class)
public interface i1 {
    void m1();
}

2. Programmatic bindings

If you need a few realizations of the same class. Similar to a qualifier. The one you asked for. https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection#Programmatic-bindings

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;

public class Module extends AbstractModule {
  protected void configure() {

    bind(i1.class)
      .annotatedWith(Names.named("c1"))
      .to(c1.class);

    bind(i1.class)
      .annotatedWith(Names.named("c2"))
      .to(c2.class);
  }
}

Later in the code

@Inject @Named("c1")
i1 i;

Guess you like

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