# 8.1.2. JAX-RS 和Jersey

如果您更喜欢 REST 端点的 JAX-RS 编程模型，则可以使用可用的实现之一而不是 Spring MVC。 [Jersey](https://jersey.github.io/)和[Apache CXF](https://cxf.apache.org/)开箱即用，运行良好。CXF 要求您在应用程序上下文中将其注册为`Servlet`或`Filter`作为 `@Bean` 。Jersey 有一些原生 Spring 支持，因此我们还在 Spring Boot 中为其提供自动配置支持以及启动器。

要开始使用 Jersey，请包含 `spring-boot-starter-jersey` 作为依赖项，然后您需要一个`ResourceConfig`类型的 `@Bean`，在其中注册所有端点，如以下示例所示：

```
@Component
public class MyJerseyConfig extends ResourceConfig {
​
    public MyJerseyConfig() {
        register(MyEndpoint.class);
    }
​
}
```

> Jersey 对扫描可执行档案的支持相当有限。例如，它无法扫描在[完全可执行的 jar 文件](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#deployment.installing)中或`WEB-INF/classes`运行可执行的 war 文件时找到的包中的端点。为了避免这种限制，不应使用`packages`方法，而应使用该`register`方法单独注册端点，如前面的示例所示。

对于更高级的自定义，您还可以注册任意数量的`ResourceConfigCustomizer`实现.

所有注册的端点都应该是带有HTTP资源注释（`@GET`和其他）的`@Components`，如下例所示：

```
@Component
@Path("/hello")
public class MyEndpoint {
​
    @GET
    public String message() {
        return "Hello";
    }
​
}
```

由于`Endpoint`是一个 Spring `@Component`，它的生命周期由 Spring 管理，您可以使用`@Autowired`注解注入依赖项，并使用`@Value`注解注入外部配置。默认情况下，Jersey servlet 已注册并映射到`/*`. 您可以通过添加`@ApplicationPath`到您的`ResourceConfig`.

默认情况下，Jersey 在名为 `jerseyServletRegistration` 的 `ServletRegistrationBean` 类型的 `@Bean`中设置为 servlet。默认情况下，Servlet 是延迟初始化的，但您可以通过设置 `spring.jersey.servlet.load-on-startup`来自定义该行为。您可以通过创建您自己的同名 bean 来禁用或覆盖该 bean。您还可以通过设置 `spring.jersey.type=filter`来使用过滤器而不是 servlet（在这种情况下，要替换或覆盖的 @Bean 是 `jerseyFilterRegistration`）。该过滤器有一个`@Order`，您可以使用`spring.jersey.filter.order` 设置它。当使用 Jersey 作为过滤器时，必须存在一个 servlet 来处理任何未被 Jersey 拦截的请求。如果您的应用程序不包含此类 servlet，您可能需要通过将`server.servlet.register-default-servlet`设置为 `true`来启用默认 servlet。 servlet 和过滤器注册都可以通过使用 `spring.jersey.init.*` 指定属性映射来指定初始化参数。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-boot-can-kao-wen-dang/8.-wang-luo/8.1.-servlet-web-ying-yong-cheng-xu/8.1.2.-jaxrs-he-jersey.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
