在播放框架中注入具有多个实现的接口
injecting interface with multiple implementations in play framework
我想使用 @Inject 注释注入 java 接口,但由于该接口有多个实现,我不知道 play 框架将如何解析 我正在尝试在 spring 但我无法在播放文档中找到类似的内容。请让我知道如何实现。
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.
}
玩框架使用Guice:
https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection
https://github.com/google/guice/wiki/Motivation
您可以通过不同的方式实现它。最简单的例子:
1。 绑定注解
如果你只需要一种实现。
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。 编程绑定
如果您需要相同的一些实现 class。类似于限定符。你要的那个。
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;
我想使用 @Inject 注释注入 java 接口,但由于该接口有多个实现,我不知道 play 框架将如何解析 我正在尝试在 spring 但我无法在播放文档中找到类似的内容。请让我知道如何实现。
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.
}
玩框架使用Guice:
https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection https://github.com/google/guice/wiki/Motivation
您可以通过不同的方式实现它。最简单的例子:
1。 绑定注解
如果你只需要一种实现。 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。 编程绑定
如果您需要相同的一些实现 class。类似于限定符。你要的那个。 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;