1

I want to create an endpoint which has a PathParam that automatically calls the constructor of an object to be injected, which has a constructor of a String argument. To spell it out in code:

Here is the resource

@GET
@Path("/{apiVersion}" + "/item")
public Response version(@PathParam("apiVersion") APIVersion apiVersion) {
    return Response.ok().build();
}

I want the String to automatically be used in a call to the APIVersion constructor. In the APIVersion class

public APIVersion(String apiVersion) {
   this.versionString = apiVersion;
}

Is it possible to do with only access to annotations? I do not have access to the ResourceConfig.

David Williams
  • 8,388
  • 23
  • 83
  • 171

1 Answers1

3

Yes, this is possible, without any annotations other than @PathParam, so the example you've given should work as-is. See https://jersey.github.io/documentation/latest/jaxrs-resources.html#d0e2271 (emphasis mine) :

In general the Java type of the method parameter may:

  1. Be a primitive type;

  2. Have a constructor that accepts a single String argument;

  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and java.util.UUID.fromString(String));

  4. Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type. or

  5. Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.

Adrian Baker
  • 9,297
  • 1
  • 26
  • 22
  • Thank you yes all of these work! And you are right, this does work as in my code sample, I had a different Jersey error that was making me think this did not work. – David Williams Aug 18 '17 at 22:24