gpt4 book ai didi

java - 在 Play Framework 中注入(inject)具有多个实现的接口(interface)

转载 作者:行者123 更新时间:2023-11-30 10:05:32 24 4
gpt4 key购买 nike

我想使用 @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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com