JAX-RS でリソースを動的ディスパッチする

Subresource Locator

JAX-RS では @Path アノテーションでリクエストURLを、@GET などのアノテーションで HTTPメソッドをマッピングします。

HTTPメソッドを指定するアノテーションを付けず、@Path アノテーションだけを定義し、戻り値としてリソースクラスを返すメソッドは、Subresource Locator になります。

例えば以下のようなリソースです。

@Path("/item")
public class ItemResource {
 
    @Path("content")
    public ItemContentResource getItemContentResource() {
        return new ItemContentResource();
    }
}

getItemContentResource() は戻り値として ItemContentResource リソースクラスを返却します。

ItemContentResource リソースクラスでは以下のようにHTTPメソッドを @GETなどのアノテーションで指定します。

public class ItemContentResource {
 
    @GET
    public Response get() { ... }
 
    @PUT
    @Path("{version}")
    public void put(@PathParam("version") int version) { ... }

}

GET /item/content というリクエストにより ItemContentResource#get() が呼び出されます。

PUT /item/content/3 というリクエストにより ItemContentResource#put() が呼び出されます。

Subresource Locator による動的ディスパッチ

Subresource Locator を利用することにより、リソースを Runtime 時に動的にディスパッチすることができます。

この場合、Subresource Locator メソッドは Object 型を返却するように定義できます。

@Path("customers")
public class CustomerResource {

    CustomerJsonResource jsonResource = new CustomerJsonResource();
    CustomerXmlResource xmlResource = new CustomerXmlResource();
    
    @Path("{type}")
    public Object getResource(@PathParam("type") String type) {
        if (type.equals("json")) {
            return jsonResource;
        } else if (type.equals("xml")) {
            return xmlResource;
        }
        return null;
    }

}

Json 形式を返却するリソース、xml 形式を返却するリソースをそれぞれ定義します。

public class CustomerJsonResource {

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_JSON})
    public Customer get(@PathParam("id") Long id) {
        return findCustomer(id);
    }
}

同様に、

public class CustomerXmlResource {

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_XML})
    public Customer get(@PathParam("id") Long id) {
        return findCustomer(id);
    }
}

GET /customers/json/999 というリスエストにはjson形式でレスポンス、 GET /customers/xml/999 というリスエストにはxml形式でレスポンス、と動的に処理を切り替えることができます。

また、ResourceMethod.Builder を使えば、リソースメソッドをプログラマティックに作成することができるため、Subresource Locator メソッドから、動的に作り上げたリソースメソッドを返却することもできます。



JavaによるRESTfulシステム構築

JavaによるRESTfulシステム構築

Developing Restful Services With Jax-rs2, Json, and Websockets

Developing Restful Services With Jax-rs2, Json, and Websockets