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

19
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;
  } 
}

假设我有上述代码,其中我扩展了Application并注册了我的资源或提供程序来设置。我想知道如何在运行时动态注入我的资源到设置中,在运行时,我的Web应用程序将创建若干个新的资源,并需要注入到Application中以便使用。

1个回答

27

用于构建资源的编程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文档


1
为什么这个答案没有被标记为正确的,我不明白。非常好的解释,谢谢! - mvreijn
我正在尝试使用Jersey 2.26 API的示例。https://jersey.github.io/apidocs/latest/jersey/index.html。这是与上面相同的示例。但似乎不能正常工作。有什么想法可以帮忙吗? - Vishwanath Washimkar
1
谢谢。我已经寻找这个有一段时间了。祝福你。 - kimathie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接