Karol
Karol

Reputation: 143

How to implement returning subresources with JAX-RS

Let us assume that we have URI schema like that:

/shop/categories
/shop/categories/{categoryId}
/shop/categories/{categoryId}/products
/shop/categories/{categoryId}/products/{productId}

The last one might look strange because it would be more intuitive to use:

/shop/products/{productId}

but it is only example. Category and Product are not real resources in my system.

I would like to implement it as two JAX-RS classes:

@Path("/shop/categories")
@Stateless
@Produces("application/xml")
public class CategoryResource {

    @EJB
    Shop shop;

    @GET
    public List<String> get() {
        return shop.getCategories();
    }

    @Path("{categoryId}")
    @GET
    public String getCategory(@PathParam("categoryId") int id) {
        return shop.getCategory(id);
    }

    @Path("{categoryId}/products")
    public CategoryProductResource getCategoryProducts(@PathParam("categoryId") int id) {
        return new CategoryProductResource(id);
    }
}

and:

@Produces("application/xml")
@Stateless
public class CategoryProductResource {

    @EJB
    Shop shop;

    int categoryId;

    public CategoryProductResource(){}

    public CategoryProductResource(int categoryId) {
        this.categoryId = categoryId;
    }

    @GET
    public List<String> get() {
        return shop.getProductsOfCategory(categoryId);
    }

    @Path("{id}")
    @GET
    public String getCategoryProduct(@PathParam("id") int id) {
        return shop.ProductOfCategory(id, categoryId);
    }
}

But the problem is that Shop is not injected into CategoryProductResource. Is there any solution to inject Shop better than passing it to constructor?

Upvotes: 4

Views: 512

Answers (1)

Xavier Coulon
Xavier Coulon

Reputation: 1600

With JAX-RS 2.0, you can do as follow:

@Path("{categoryId}/products")
public CategoryProductResource getCategoryProducts(
             @PathParam("categoryId") int id,
             @Context ResourceContext rc) {
    return rc.initResource(new CategoryProductResource(id));
}

In that case, I think the @Stateless annotation is not required on the CategoryProductResource.

HTH.

Upvotes: 4

Related Questions