Jersey - 用于注入的 @Context 注释。它是如何运作的?
我正在查看一个很好的使用 Jersey 的 REST 教程。 在页面下方,有一个名为 TodoResource
的 Web 资源,它本身包含两个实例变量,
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
和 Request 实例变量初始化了吗?我知道使用
@Context
注释允许注入信息,但是什么时候会发生这种情况? Jersey 会自动处理吗?
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;
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了一些有趣的结果 注射规则,这是我发现的内容:
我希望这会有所帮助。
I've run into some interesting results with the Rules of Injection, here's what I've found:
I hope this helps.
Jersey 不会修改该类,但它会根据客户端的每个请求创建它。
调用类构造函数后,将注入上下文字段。
(如果您尝试访问构造函数内的这些字段,它们将为
null
)在您的情况下,该类不需要特定的构造函数,因此只需:
但在方法内部(代表网络资源)用
@POST, @GET, ...
注释,您将有权访问上下文字段。Jersey doesn't modify the class, but it creates it on every request from the client.
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:
But inside methods (which represent web-resources) annotated with
@POST, @GET, ...
you would have access to context fields.使用@PostConstruct方法注释:
Use @PostConstruct method annotation: