java - JAX-RS Jersey,如何向应用程序动态添加资源或提供者

标签 java rest jersey jax-rs

public class ShoppingApplication extends Application {

  private Set<Object> singletons = new HashSet<>();
  private Set<Class<?>> classes = new HashSet<>();

  public ShoppingApplication() {
    classes.add(CustomerResourceService.class);
    classes.add(JAXBMarshaller.class);
    classes.add(JSONMarshaller.class);
    singletons.add(new CustomerResourceService());
  }

  @Override
  public Set<Class<?>> getClasses() {
    return classes;
  }

  @Override
  public Set<Object> getSingletons() {
    return singletons;
  } 
}

假设我有上面的代码,我扩展了应用程序并注册了我的资源或提供者来设置。我想知道如何动态注入(inject)我的资源以在运行时设置,我的 Web 应用程序将在运行时创建几个新资源并且需要注入(inject)到应用程序才能使用。

最佳答案

用于构建资源的编程 API

Resource类是你正在寻找的。请注意,它是 Jersey 特定的 API。

根据文档,Resource类是编程资源建模 API 的主要入口点,它提供了以编程方式扩展现有 JAX-RS 注释资源类或构建可由 Jersey 运行时使用的新资源模型的能力。

查看文档提供的示例:

@Path("hello")
public class HelloResource {

     @GET
     @Produces("text/plain")
     public String sayHello() {
         return "Hello!";
     }
}
// Register the annotated resource.
ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class);

// Add new "hello2" resource using the annotated resource class
// and overriding the resource path.
Resource.Builder resourceBuilder =
        Resource.builder(HelloResource.class, new LinkedList<ResourceModelIssue>())
        .path("hello2");

// Add a new (virtual) sub-resource method to the "hello2" resource.
resourceBuilder.addChildResource("world")
        .addMethod("GET")
        .produces("text/plain")
        .handledBy(new Inflector<Request, String>() {

                @Override
                public String apply(Request request) {
                    return "Hello World!";
                }
        });

// Register the new programmatic resource in the application's configuration.
resourceConfig.registerResources(resourceBuilder.build());

下表说明了上面示例中配置的应用程序支持的请求和提供的响应:

  Request              |  Response        |  Method invoked
-----------------------+------------------+----------------------------
   GET /hello          |  "Hello!"        |  HelloResource.sayHello()
   GET /hello2         |  "Hello!"        |  HelloResource.sayHello()
   GET /hello2/world   |  "Hello World!"  |  Inflector.apply()

有关更多详细信息,请查看 Jersey documentation .

关于java - JAX-RS Jersey,如何向应用程序动态添加资源或提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26881986/

相关文章:

java - 将字符串转换为字节 - Java

java - 为什么数组不可扩展?

用于使用 Facebook token 进行身份验证的无状态 REST 端点的 Spring 社交身份验证过滤器

iphone - 从 Google App Engine 的数据存储中获取实体以用于 iOS 应用

rest - soapUI:带有文件附件的多部分/表单数据 REST 请求

java - Jersey Java Web 服务 XML

java - 如何让 float 保留到小数点后两位?前- 25.00000

java - 我将如何更改文档中图标上的悬停文本? ( java )

java.lang.ClassNotFoundException : org. glassfish.jersey.client.JerseyClientBuilder

java - 在 Eclipse 控制台中显示 Grizzly 异常