JAX-RS Jersey, how to dynamic adding resources or providers to Application

前端 未结 1 1628
萌比男神i
萌比男神i 2021-02-05 12:58
public class ShoppingApplication extends Application {

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


        
      
      
      
1条回答
  •  -上瘾入骨i
    2021-02-05 13:29

    Programmatic API for building resources

    The Resource class is what your are looking for. Just mind it's a Jersey specific API.

    According to the documentation, the Resource class is the main entry point to the programmatic resource modeling API that provides ability to programmatically extend the existing JAX-RS annotated resource classes or build new resource models that may be utilized by Jersey runtime.

    Have a look at the example provided by the documentation:

    @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())
            .path("hello2");
    
    // Add a new (virtual) sub-resource method to the "hello2" resource.
    resourceBuilder.addChildResource("world")
            .addMethod("GET")
            .produces("text/plain")
            .handledBy(new Inflector() {
    
                    @Override
                    public String apply(Request request) {
                        return "Hello World!";
                    }
            });
    
    // Register the new programmatic resource in the application's configuration.
    resourceConfig.registerResources(resourceBuilder.build());
    

    The following table illustrates the supported requests and provided responses for the application configured in the example above:

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

    For additional details, check the Jersey documentation.

    0 讨论(0)
提交回复
热议问题