JAX-RS 中的 Provider 是什么意思?

2022-01-21 00:00:00 java jax-rs jersey

谁能向我解释一下 JAX-RS Provider 是什么以及@Provider"注释的作用是什么?我一直在阅读文档,但我无法得到它.
如果有资源类为传入的请求提供服务,那么 Providers 会做什么?当我创建持久资源类(不是按请求的资源类)时,它们与单例资源类有何不同?还是这些类也是提供者?

Could anyone explain to me what a JAX-RS Provider is and what ‘@Provider’ annotation does? I have been reading documentation but I cant get it.
If there are resource classes that service the incoming requests, what do Providers do? How are they different from singleton resource classes when I create a persistent resource class (the one that is not per-request)? Or are those classes also providers?

推荐答案

提供程序是一种扩展和自定义 JAX-RS 运行时的简单方法.您可以将它们视为(可能)改变运行时行为的插件,以实现一组(程序定义的)目标.

Providers are a simply a way of extending and customizing the JAX-RS runtime. You can think of them as plugins that (potentially) alter the behavior of the runtime, in order to accomplish a set of (program defined) goals.

提供者不与资源类相同,从概念上讲,它们存在于资源类和 JAX-RS 实现之间的级别.如果有帮助,您可以将它们视为设备驱动程序(存在于用户和内核空间之间).这是一个广泛的概括.

Providers are not the same as resources classes, they exist, conceptually, at a level in-between resources classes and the JAX-RS implementation. If it helps, you can think of them in the same light as device drivers (existing between user and kernel space). This is a broad generalization.

当前的 JAX-RS 规范定义了三类提供程序.它们之间的共同点是所有提供者都必须通过@Provider 注解来标识,并遵循一定的构造函数声明规则.除此之外,不同的提供者类型可能有额外的注解,并且会实现不同的接口.

There are three classes of providers defined by the current JAX-RS specification. The commonality between them is that all providers must be identified by the @Provider annotation and follow certain rules for constructor declaration. Apart from that, different provider types may have additional annotations, and will implement different interfaces.

实体提供者

这些提供程序控制数据表示(如 XML、JSON、CSV)与其 Java 对象等价物的映射.

These providers control the mapping of data representations (like XML, JSON, CSV) to their Java object equivalents.

上下文提供者

这些提供者通过@Context 注解控制资源可以访问的上下文.

These providers control the context that resources can access via @Context annotations.

异常提供程序

这些提供程序控制 Java 异常到 JAX-RS 响应实例的映射.

These providers control the mapping of Java exceptions to a JAX-RS Response instance.

您的运行时将附带许多预定义的提供程序,它们将负责实现基本级别的功能(例如,映射到 XML 和从 XML 映射、转换最常见的异常等).您还可以根据需要创建自己的提供程序.

Your runtime will come with a number of predefined providers that will be responsible for implementing a base level of functionality (e.g for mapping to and from XML, translating the most common exceptions etc etc). You can also create your own providers as needed.

JAX-RS 规范 是阅读这些不同提供程序类型及其作用的很好参考(参见第 4 章).

The JAX-RS specification is a good reference for reading up on these different provider types and what they do (see Chapter 4).

相关文章