@Context 对象来自哪里

Where do @Context objects come from(@Context 对象来自哪里)

本文介绍了@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:

  1. 如果您的应用使用类路径扫描(或包扫描),请确保提供程序位于正确的包/类路径中
  2. 或者您可以简单地使用 META-INF/services 条目注册它(添加 META-INF/services/com.sun.jersey.spi.inject.InjectableProvider 文件,其中包含您的提供程序类的名称)

这篇关于@Context 对象来自哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:@Context 对象来自哪里

基础教程推荐