Jersey - 注入的@Context注释。它是如何工作的? [英] Jersey - The @Context annotation for injection. How does it work?
问题描述
我正在使用Jersey查看一个很好的 REST教程。
在页面下方,有一个构建的Web资源,名为 TodoResource
,它本身包含两个实例变量
I was looking at a good REST tutorial using Jersey.
Down the page, there is a web resource that is built which is entitled TodoResource
which itself contains two instance variables
public class TodoResource {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public TodoResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
}
我想知道 UriInfo
和请求
实例变量是否已初始化?我知道使用 @Context
注释可以注入信息,但这会发生在什么时候?这会由泽西自动处理吗?
I was wondering exactly how the UriInfo
and Request
instance variables are initialized? I know that using the @Context
annotation allows for information to be injected, but at what point does this happen? Will this be handled automatically by Jersey?
推荐答案
泽西岛不会修改这个类,但它在客户端的每个请求中创建。
调用类构造函数后,将注入上下文字段。$
(你应该尝试访问构造函数中的那些字段,它们将是 null
)
After the class constructor was invoked, the context fields are injected.
(Should you try to access those fields inside the constructor, they will be null
)
在你的情况下,该类不需要特定的构造函数,所以只需:
In your case, the class wouldn't need a specific constructor, so just:
public TodoResource () {
// in most cases the ctor stays empty.
// don't do much work here, remember: the ctor is invoked at every client request
}
但是用 @POST,@ GET,...
注释的内部方法(代表网络资源)你可以访问上下文字段。
But inside methods (which represent web-resources) annotated with @POST, @GET, ...
you would have access to context fields.
这篇关于Jersey - 注入的@Context注释。它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!