Java/Quarkus:如何注入返回相同数据类型的不同实例



我在一个有点棘手的情况下,我有2个方法在我的QuarkusRESTApplication两者返回相同的数据类型。但是,我想把它们注入到两个不同的变量中。

如果只有一个方法和一个变量,那么一切都很好,但由于有2个方法,而且它们都返回相同的类型,Quarkus无法识别要注入哪个,并运行到错误:

Ambiguous dependencies for type String and qualifiers [@Default]
下面是我的代码:类,它有@Produces,它将提供所需的依赖项:
@ApplicationPath("/")
public class RESTApplication extends Application {
@Produces
public String firstMethod() {
System.out.println("firstMethod : returns Hello One");
return "HELLO ONE";
}
@Produces
public String secondMethod() {
System.out.println("secondMethod : returns Hello TWO");
return "HELLO TWO";
}
}

下面是我注入返回值的类:

@Path("/api")
public class RestAPI {
@Inject
String one;
@Inject
String two;
@Path("/one")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String myMethodOne(final String input) {
System.out.println("One : " + one)
return one;
}
@Path("/two")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String myMethodOne(final String input) {
System.out.println("Two : " + two)
return two;
}
}

正如你所看到的,这两个方法都返回相同的类型,所以夸克不知道该注入哪一个。有没有区分的方法?

如果我在RestApplication中删除第二种方法,那么一切都可以完美地工作。在我的项目中,我需要根据一些计算返回相同类型的不同值,所以我需要使用这样的东西。

基于OP的代码,以免太长

Java:

@Qualifier // Create Qualifier annotation
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Blah {}
...
@Produces
@Blah // Add it
public String firstMethod() {
...
@Inject
@Blah // Qualify it
String one;

芬兰湾的科特林:

@Qualifier // Create Qualifier annotation
@Retention
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION, AnnotationTarget.FIELD, AnnotationTarget.CLASS, AnnotationTarget.VALUE_PARAMETER) // Not all are needed
annotation class Blah
...
@Produces
@Blah // Add it
fun firstMethod(): String {
...
// As a constructor parameter
class RestAPI(@Blah private val one: String) {
// OR as a field
@Inject
@field:Blah
lateinit var one: String

最新更新