我想使用 @Inject 注释注入(inject) java 接口(interface),但由于此接口(interface)有多个实现,我不知道 play 框架将如何解析 我试图在 spring 中找到类似限定符注释的东西,但找不到东西在 Play 文档中就像这样。请告诉我如何实现这一目标。
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.
}
最佳答案
Play Framework 使用Guice:
https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection https://github.com/google/guice/wiki/Motivation
您可以通过不同的方式实现它。最简单的例子:
1. 绑定(bind)注解
如果你只需要一种实现。 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。 程序化绑定(bind)
如果你需要同一个类的几个实现。类似于限定符。你要的那个。 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);
}
}
后面的代码
@Inject @Named("c1")
i1 i;
关于java - 在 Play Framework 中注入(inject)具有多个实现的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218122/