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/