在Play框架中注入具有多个实现的接口

我想使用@Inject注释注入java接口,但由于此接口有多个实现,因此我无法获得play框架将如何解决,我试图在春季找到类似限定符注释的东西,但无法在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.

}


莫回无
浏览 103回答 1
1回答

天涯尽头无女友

玩框架使用 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-annotationsimport com.google.inject.ImplementedBy;@ImplementedBy(c1.class)public interface i1 {    void m1();}2. 编程绑定如果您需要同一类的一些实现。类似于限定符。你要求的那个。https://www.playframework.com/documentation/2.7.x/JavaDependencyInjection#Programmatic-bindingsimport 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;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java