Java Spring + Jersey子资源:在运行时注入Constructor-arg [英] Java Spring + Jersey subresource: inject constructor-arg at runtime
问题描述
我定义了以下方法,返回一个代表子资源定位器(Jersey)的bean:
I have the following method defined, returning a bean that represents a subresource locator (Jersey):
@Path("{slug}")
public PageResource page(
@PathParam("slug") String siteSlug) throws AppException {
siteService.getSiteBySlug(siteSlug); //Validate if exists, else throw error
return (PageResource) appContext.getBean("pageResource", siteSlug);
}
pageResource
具有在applicationContext.xml
中定义的原型范围.
pageResource
has prototype scope defined in applicationContext.xml
.
问题:在运行时传递构造器参数时,将Bean注入当前类的替代方法是什么?
我不愿意从应用程序上下文中显式地获取bean.
Question: what is the alternative way for injecting the bean into the current class, while passing the constructor-arg at runtime?
I'm not comfortable getting the bean explicitly from the application context.
编辑@peeskillet:
Edit for @peeskillet:
子资源:
public class PageResource {
@Autowired
IPageService pageService;
String siteSlug;
public void setPageService(IPageService pageService){
this.pageService = pageService;
}
public PageResource(){}
public PageResource(String siteSlug){ //***Inject siteSlug from parent here***
this.siteSlug = siteSlug;
};
@POST
@Path("/pages")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response createPage(@NotNull @Valid Page page) throws AppException{
System.out.println(pageService);
ObjectId pageId = pageService.createPage(page);
page.setId(pageId);
return Response
.status(Response.Status.CREATED)// 201
.entity(page)
.header("Location",
"http://localhost:8000/zwoop-v001/sites/" + this.siteSlug +
"/pages/" + page.getSlug()).build();
}
}
推荐答案
What you can do is inject ResourceContext
, and resolve the sub-resource instance through that.
当子资源定位器方法返回托管资源类的实例时,可以利用资源上下文.就像根资源类的实例一样,此类实例将在声明的范围内注入和管理.
The resource context can be utilized when instances of managed resource classes are to be returned by sub-resource locator methods. Such instances will be injected and managed within the declared scope just like instances of root resource classes.
如前所述,您可以获得子资源类的实例,并且所有注入都将得到处理
As stated, you can obtain instances of your sub-resources classes, and all the injections will be handled
@Path("root")
public class Resource {
@Context
ResourceContext context;
@Path("sub/{id}")
public SubResource get() {
return context.getResource(SubResource.class);
}
}
@PathParam
也可以作为注入子资源实例的解析.所以你可以做
@PathParam
s are also resolved as injections into your sub-resource instance. So you could just do
class SubResource {
@Autowired
Service service;
@PathParam("id")
long id;
}
当子资源实例得到解析时,它将被注入服务和路径参数.
And when the sub-resource instance gets resolved, it will be injected with the service and the path param.
这篇关于Java Spring + Jersey子资源:在运行时注入Constructor-arg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!