Where do @Context objects come from(@Context 对象来自哪里)
问题描述
我一直在到处寻找,但似乎找不到明确的答案......
I've been searching everywhere, but can't seem to find a clear answer...
服务器(我的问题是 glassfish)注入带有 @Context 注释的实际对象的机制是什么?更具体地说,如果我想编写一个执行以下操作的类:
What is the mechanism whereby a server (glassfish for my problem) injects actual objets that are annotated with @Context? More specifically, if I wanted to write a class that did something like:
@Path("/")
public class MyResource {
@GET
public String doSomething(@Context MyObject obj) {
// ...
}
}
那我该怎么做呢?MyObject 是在哪里实例化的,由谁实例化,如何实例化?
then how would I do it? Where is it that the MyObject is instanciated, who does it, and how?
我见过类似以下的东西:
I've seen stuff like the following:
在 JAX-RS 中使用 @Context、@Provider 和 ContextResolver
http://jersey.576304.n2.nabble.com/ContextResolver-confusion-td5654154.html
但是,这与我所看到的不符,例如在 org.neo4j.server.rest.web.RestfulGraphDatabase 的构造函数中,签名如下:
However, this doesn't square with what I've seen, e.g. in the constructor of org.neo4j.server.rest.web.RestfulGraphDatabase, which has the following signature:
public RestfulGraphDatabase(
@Context UriInfo uriInfo,
@Context Database database,
@Context InputFormat input,
@Context OutputFormat output,
@Context LeaseManager leaseManager )
推荐答案
您可以编写自己的注入提供程序并将其插入 Jersey - 查看 SingletonTypeInjectableProvider 和 PerRequestTypeInjectableProvider - 扩展这些类之一(取决于您想要的可注入对象的生命周期)并将您的实现注册为 Web 应用程序中的提供者.
You can write your own injection provider and plug that into Jersey - look at SingletonTypeInjectableProvider and PerRequestTypeInjectableProvider - extend one of these classes (depending on the lifecycle you want for the injectable object) and register your implementation as a provider in your web app.
例如,像这样的:
@Provider
public class MyObjectProvider extends SingletonTypeInjectableProvider<Context, MyObject> {
public MyObjectProvider() {
// binds MyObject.class to a single MyObject instance
// i.e. the instance of MyObject created bellow will be injected if you use
// @Context MyObject myObject
super(MyObject.class, new MyObject());
}
}
要将提供程序包含在您的网络应用程序中,您有多种选择:
To include the provider in your web app you have several options:
- 如果您的应用使用类路径扫描(或包扫描),请确保提供程序位于正确的包/类路径中
- 或者您可以简单地使用 META-INF/services 条目注册它(添加 META-INF/services/com.sun.jersey.spi.inject.InjectableProvider 文件,其中包含您的提供程序类的名称)
这篇关于@Context 对象来自哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:@Context 对象来自哪里
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01