我可以在同一个 class 的两个方法中使用 @GET 注释吗?

Can I use @GET annotations in two methods in same class?

@GET
@Produces(MediaType.APPLICATION_JSON)
public String getRscSubTypes(){
    return AddResourceMysql.getRscSubType();
}    

@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getDbTypes() {
    return AddResourceMysql.getDbType();
}

这将返回以下异常:

org.glassfish.jersey.server.model.ModelValidationException: 
Validation of the application resource model has failed during application initialization.

你能帮帮我吗?

如果你想定义多个资源方法,在同一个 MIME type 中处理同一个 MIME type 的 GET 请求,你必须为这些方法指定不同的子路径:

@Path("rcsubtypes")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getRscSubTypes()
{
    return AddResourceMysql.getRscSubType();
}  

@Path("dbtypes") 
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getDbTypes()
{
    return AddResourceMysql.getDbType();
}

在 class 的 @Path annotation of this method, is a subpath of the path specified in the @Path 注释中指定的路径,它是您为应用程序定义的路径的子路径。

为了解释你的行为,总是调用第二种方法,如果没有 @Consumes annotation present on the first method: @Consumes defines which media type (set in the Content-Type header of the request) can be accepted by the method. Without a @Consumes 注释,所有请求都会被接受,但我认为,如果一个方法指定了一个接受的媒体类型,它将是首选。

球衣文档中的匹配部分:3.1. Root Resource Classes

请求匹配的工作原理

当然,您可以在同一个 class 中使用多个 @GET 注释的方法。但是,您当前的定义是模棱两可

如需更多说明,请查看 JAX-RS 2.0 specification:

3.7.2 Request Matching

A request is matched to the corresponding resource method or sub-resource method by comparing the normalized request URI, the media type of any request entity, and the requested response entity format to the metadata annotations on the resource classes and their methods. [...]

如何修复

您需要更改方法注释以确保没有歧义。为此,您可以使用以下注释:

例如,要修复它,您只需为每个方法添加一个具有不同值的 @Path 注释。