问题
I've already seen the following question on how to inject @Context
dependencies into Jersey resource constructors. But my question is slightly different -- I'd like to inject a @PathParam
String. I have a class resembling the following:
@Path("foo/{fooId}/bar")
public class BarResource {
@Inject
public BarResource(@PathParam("fooId") String foo, Service service) {
...
}
...
}
The Service
is injected fine by Guice, but the path segment is always null. This actually surprises me; if anything I assumed Guice would loudly explode complaining about an unresolvable dependency.
How can I inject a path parameter in this manner? I would prefer to avoid field injection for the purposes of keeping these resource classes unit-testable.
回答1:
It appears that @PathParam
is not acceptable by default as a Constructor
argument. This new feature document states
The arguments allowed in a resource class constructor depends on the resource provider used to create an instance of the resource class [...]. For default per-request resource classes you can use any combination of parameters annotated with UriParam, UriParam, QueryParam, MatrixParam, HeaderParam or HttpContext.
You could provide your own resource provider that processes the @PathParam
annotation.
来源:https://stackoverflow.com/questions/18489529/how-can-i-mix-guice-and-jersey-injection