为什么我们不能在 Class(RCC) 级别声明任何 *Params 注释,同时在 Jax-RS 中同时声明@Singleton

Why we can't declare any *Params Annotaion at Class(RCC) level, while declaring @Singleton at a same time in Jax-RS

将根资源 Class 作为 @Singleton 并在 Class 级别同时声明 @QueryParam 注释时,

@Singleton
@Path("/")
public class MyResource{

    @QueryParam("q1") String q1;

    @Path("/test")
    public Response getQueryParam(){

        return Response.entity(q1).build;   
    }
}

我在请求时收到 500 错误代码的异常,如果有人知道此异常的原因,请帮助我。

SEVERE: StandardWrapper.Throwable
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) 

根据 Example 3.24

中的 docs

will cause validation failure during application initialization as singleton resources cannot inject request specific parameters. The same example would fail if the query parameter would be injected into constructor parameter of such a singleton. In other words, if you wish one resource instance to server more requests (in the same time) it cannot be bound to a specific request parameter.

因为 QueryParam 请求特定的 你不能将它与 @Singleton

一起使用

@上下文来拯救!

好消息是你可以注入其他类型的对象,这些对象可以使用 @Context 注释注入,代理对象用于这些;因此允许在单例中使用:

@Context
private UriInfo urinfo;

private String queryparam;

@GET
@Produces(value = MediaType.APPLICATION_JSON)
public Response bla(){

    MultivaluedMap<String, String> params = urinfo.getQueryParameters(true);

    queryparam = params.containsKey("yourparam") ? 
                            params.get("yourparam").get(0) 
                            : "not in request";

    return Response.ok(queryparam).build();
}