java 使用 Jersey 在 Restful Resource 中使用多个 @PathParams 时未发现注入源错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25736819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:34:13  来源:igfitidea点击:

no injection source found error when using multiple @PathParams in Restful Resource using Jersey

javarestjerseyjax-rsjersey-2.0

提问by vpitts

I am working on a simple Restful web service using Rest / Jersey with Tomcat 7. Things are working just fine if all of my Paths include a single parameter. If I include one that uses more than one parameter, I encounter the "No injection source found" error when I try to hit any of the resource paths supported by my resource class - even those that were working before. If I comment out that particular piece of code, all of my other paths work as expected. But if I uncomment out that piece of code, I cannot use ANY of the my paths.

我正在使用 Rest/Jersey 和 Tomcat 7 开发一个简单的 Restful Web 服务。如果我的所有路径都包含一个参数,那么一切都很好。如果我包含一个使用多个参数的参数,当我尝试访问我的资源类支持的任何资源路径时,我会遇到“未找到注入源”错误——即使是那些以前工作过的资源路径。如果我注释掉那段特定的代码,我的所有其他路径都会按预期工作。但是如果我取消注释那段代码,我就不能使用我的任何路径。

Here is a snippet of my code:

这是我的代码片段:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// get all the information about a specific item
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String getItem(@PathParam("id") String itemId)
{
    String answer = "{";
    answer += "\"itemid\":\"" + itemId + "\",";
    answer += "\"type\":0,";
    answer += "\"sector\":322948,";
    answer += "\"created\":53249098220";
    answer += "}";

    return answer;
}

// if I comment out this method, all is fine; 
// if I leave it in, error is thrown when I make any restful call
// query to see if there is a new item for user
@Path("/loc/{userid}/{xloc}/{yloc}")
@Produces(MediaType.APPLICATION_JSON)
public String getNewitem(@PathParam("userid") String userId,
    @PathParam("xloc") Number xLoc,
    @PathParam("yloc") Number yLoc)
{
    String answer = "{\"itemid\":\"abcdefgh\"}";
    return answer;
}

Here is the error trace:

这是错误跟踪:

javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)
root cause

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

[[FATAL] No injection source found for a parameter of type public java.lang.String com.drunkware.geobijous.resources.GBBijouResource.getNewBijou(java.lang.String,java.lang.Number,java.lang.Number) at index 1.; source='ResourceMethod{httpMethod=GET, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.drunkware.geobijous.resources.GBBijouResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@757bdd3c]}, definitionMethod=public java.lang.String com.drunkware.geobijous.resources.GBBijouResource.getNewBijou(java.lang.String,java.lang.Number,java.lang.Number), parameters=[Parameter [type=class java.lang.String, source=userid, defaultValue=null], Parameter [type=class java.lang.Number, source=latitude, defaultValue=null], Parameter [type=class java.lang.Number, source=longitude, defaultValue=null]], responseType=class java.lang.String}, nameBindings=[]}']
        org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:467)
        org.glassfish.jersey.server.ApplicationHandler.access0(ApplicationHandler.java:163)
        org.glassfish.jersey.server.ApplicationHandler.run(ApplicationHandler.java:323)
        org.glassfish.jersey.internal.Errors.call(Errors.java:289)
        org.glassfish.jersey.internal.Errors.call(Errors.java:286)
        org.glassfish.jersey.internal.Errors.process(Errors.java:315)
        org.glassfish.jersey.internal.Errors.process(Errors.java:297)
        org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
        org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
        org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:285)
        org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:311)
        org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
        org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
        javax.servlet.GenericServlet.init(GenericServlet.java:158)
        org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
        org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
        org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
        org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
        java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        java.lang.Thread.run(Unknown Source)

Any suggestions to get around this problem? I am using jersey 2.12. Is this a known bug?

有什么建议可以解决这个问题吗?我正在使用球衣 2.12。这是一个已知的错误?

回答by Marcio Jasinski

The injection error you receive is caused by Numberparameters. Since complex objects like Number are not supported in @PathParam implementation. You could easily fix this by the following code (also add the @GET)

您收到的注入错误是由Number参数引起的。由于@PathParam 实现不支持像 Number 这样的复杂对象。您可以通过以下代码轻松解决此问题(同时添加@GET)

@GET
@Path("loc/{userid}/{xloc}/{yloc}")
public String getNewitem(@PathParam("userid") String userId,
    @PathParam("xloc") int xLoc,
    @PathParam("yloc") int yLoc)
{
    String answer = "{\"itemid\":\"abcdefgh\"}";
    return answer;
}

There are many ways to work with complex objects in case you need more information than intcan provide you. But then you must change the way to receive them since @PathParamis quite simple. For more details regarding complex usage, check Hymansonto help you with object/json conversion. You probably will have something like this:

有许多方法可以处理复杂对象,以防您需要的信息超出了int所能提供的范围。但是你必须改变接收它们的方式,因为@PathParam这很简单。有关复杂用法的更多详细信息,请查看Hymanson以帮助您进行 object/json 转换。你可能会有这样的事情:

@POST
@Path("loc/{userid}")
public String createNewitem(@PathParam("userid") String userId, MyLocalization aLoc)
{
    String answer = "{\"itemid\":\"abcdefgh\"}";
    return answer;
}

The class MyLocalizationis a pojo that you will create to be handled by Hymanson libs with following dependency:

该类MyLocalization是一个 pojo,您将创建它以由具有以下依赖项的Hymanson libs 处理:

  <dependency>
    <groupId>com.fasterxml.Hymanson.jaxrs</groupId>
    <artifactId>Hymanson-jaxrs-json-provider</artifactId>
    <version>2.2.3</version>
  </dependency>