gpt4 book ai didi

Java Spring + Jersey 子资源 : inject constructor-arg at runtime

转载 作者:行者123 更新时间:2023-12-01 21:24:39 25 4
gpt4 key购买 nike

我定义了以下方法,返回一个表示子资源定位器( Jersey )的 bean:

@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 中定义的原型(prototype)范围。

问题:在运行时传递构造函数参数的同时将 bean 注入(inject)当前类的替代方法是什么?
我不习惯从应用程序上下文中显式获取 bean。

编辑@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();
}
}

最佳答案

你能做的就是注入(inject)ResourceContext ,并通过它解析子资源实例。

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.

如上所述,您可以获得子资源类的实例,并且所有注入(inject)都将被处理

@Path("root")
public class Resource {

@Context
ResourceContext context;

@Path("sub/{id}")
public SubResource get() {
return context.getResource(SubResource.class);
}
}

@PathParam 也被解析为注入(inject)到您的子资源实例中。所以你可以这样做

class SubResource {

@Autowired
Service service;

@PathParam("id")
long id;
}

当子资源实例被解析时,它将被注入(inject)服务和路径参数。

关于Java Spring + Jersey 子资源 : inject constructor-arg at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com