Close

JAX-RS - Resource Constructors

[Updated: Apr 30, 2017, Created: Apr 30, 2017]

A constructor of the resource class (registered as instance-per-request) may include parameters annotated with one of the following:
@Context, @HeaderParam, @CookieParam, @MatrixParam, @QueryParam or @PathParam.

JAX-RS runtime will inject their values, just like it does for resource method parameters.

Let's understand that with an example.

Example

@Path("/")
public class MyResource {
  private final UriInfo uriInfo;
  private String qValue;
  private int pathNum;

  public MyResource(@Context UriInfo uriInfo,
                    @PathParam("num") int pathNum,
                    @QueryParam("q") String qValue) {
      this.pathNum = pathNum;
      this.uriInfo = uriInfo;
      this.qValue = qValue;
  }

  @GET
  @Path("/test{num:[1-9]{0,1}}")
  public String handleRequest() {
      URI uri = uriInfo.getRequestUri();
      return String.format(" response from: %s%n PathNum: %s%n q: %s%n",
              uri, pathNum, qValue);
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run

Let's write a JAX-RS client to test above resource:

public class MyClient {
  public static void main(String[] args) {
      Client client = ClientBuilder.newClient();
      WebTarget target = client.target("http://localhost:8080/test9");
      String response = target.queryParam("q", "testVal")
                              .request()
                              .get(String.class);
      System.out.println(response);
  }
}

Output

 response from: http://localhost:8080/test9?q=testVal
PathNum: 9
q: testVal

Singleton class and constructor parameters

Note that, for a singleton resource class per-request information may not make sense in a constructor. Also it is not possible to pass request time parameters during the construction time in the Application subclass:

@ApplicationPath("/")
public class MyRestApp extends Application {
  .....

    @Override
    public Set<Object> getSingletons() {
        Set<Object> set = new HashSet<>();
        set.add(new MyResource());//not possible to pass request time parameters here
        return set;
    }
    ..
}

Using multiple constructors

More than one public constructor can be defined with different permissible parameters. The runtime implementation uses the one with the most matching parameters. If there are various constructors with the same number of parameters then the it's up to JAX-RS implementation which one to choose. According to the specification, the implementation should generate a warning about such ambiguity.

Example Project

Dependencies and Technologies Used:

  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • JDK 1.8
  • Maven 3.3.9

Resource Constructor Example Select All Download
  • jaxrs-resource-constructors
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also