Java 如何用JAX-RS实现返回子资源
假设我们有这样的URI模式:Java 如何用JAX-RS实现返回子资源,java,dependency-injection,jax-rs,Java,Dependency Injection,Jax Rs,假设我们有这样的URI模式: /shop/categories /shop/categories/{categoryId} /shop/categories/{categoryId}/products /shop/categories/{categoryId}/products/{productId} 最后一个可能看起来很奇怪,因为使用它会更直观: /shop/products/{productId} 但这只是一个例子。类别和产品在我的系统中不是真正的资源 我想将其实现为两个JAX-RS类:
/shop/categories
/shop/categories/{categoryId}
/shop/categories/{categoryId}/products
/shop/categories/{categoryId}/products/{productId}
最后一个可能看起来很奇怪,因为使用它会更直观:
/shop/products/{productId}
但这只是一个例子。类别和产品在我的系统中不是真正的资源
我想将其实现为两个JAX-RS类:
@Path(“/shop/categories”)
@无国籍
@生成(“应用程序/xml”)
公共类类别资源{
@EJB
商店;
@得到
公共列表get(){
return shop.getCategories();
}
@路径(“{categoryId}”)
@得到
公共字符串getCategory(@PathParam(“categoryId”)int-id){
退货商店。getCategory(id);
}
@路径(“{categoryId}/产品”)
公共CategoryProductResource getCategoryProducts(@PathParam(“categoryId”)int-id){
返回新的CategoryProductResource(id);
}
}
以及:
@产生(“应用程序/xml”)
@无国籍
公共类CategoryProductResource{
@EJB
商店;
int分类;
公共类别ProductResource(){}
公共CategoryProductResource(int categoryId){
this.categoryId=categoryId;
}
@得到
公共列表get(){
退货商店。getProductsOfCategory(categoryId);
}
@路径(“{id}”)
@得到
公共字符串getCategoryProduct(@PathParam(“id”)int-id){
退货商店。产品类别(id,categoryId);
}
}
但问题是,Shop
没有被注入到CategoryProductResource
中。
有没有比将其传递给构造函数更好的解决方案来注入
Shop
使用JAX-RS 2.0,您可以执行以下操作:
@Path("{categoryId}/products")
public CategoryProductResource getCategoryProducts(
@PathParam("categoryId") int id,
@Context ResourceContext rc) {
return rc.initResource(new CategoryProductResource(id));
}
在这种情况下,我认为类别ProductResource
上不需要@Stateless
注释
嗯