使用 Jersey 在 web.xml 中配置提供程序包

Configuring provider packages in web.xml with Jersey

我正在处理网络服务,但遇到了非常奇怪的错误。 这是我的 web.xml:

<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>service</param-value>
</init-param>

据我所知,<param-value> 必须引用到我的主要应用程序所在的包中。但是,我的应用程序在 rest.main 包中,但 Web 服务仅适用于上面定义的 service 值。

有什么问题,有人可以向我解释这些行吗?

如果应用程序只包含存储在特定包中的资源和提供程序,Jersey 可以扫描它们并自动注册。

<web-app>
<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>org.foo.rest;org.bar.rest</param-value>
    </init-param>
    ...
</servlet>
...
</web-app>

param-value指的是自动扫描的包。

查看 documentation regarding the jersey.config.server.provider.packages 配置 属性:

Defines one or more packages that contain application-specific resources and providers. If the property is set, the specified packages will be scanned for JAX-RS root resources and providers.

Servlet 2.x 容器

此设置在 web.xml 部署描述符中经常使用,以指示 Jersey 扫描这些包并自动注册任何找到的资源和提供程序:

<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        org.foo.myresources,org.bar.otherresources
    </param-value>
</init-param>

使用此设置,Jersey 将自动发现所选包中的资源和提供程序。默认情况下,Jersey 也会递归扫描子包。

Servlet 3.x 容器

对于 Servlet 3.x 容器,根本不需要 web.xml。相反,@ApplicationPath annotation can be used to annotate a custom Application or ResourceConfig 子类并为应用程序中配置的所有 JAX-RS 资源定义基本应用程序 URI。

使用以下内容定义将被扫描的包:

@ApplicationPath("resources")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("org.foo.myresources,org.bar.otherresources");
    }
}

有关更多详细信息,请查看 Jersey 文档的 deployment section

重要

  • 始终使用包的限定名称;
  • 声明多个包时使用,;作为分隔符。

你只需要将包名添加到

如果我将我的资源 class 放在 com.ft.resources 包中,请形成示例 然后我必须在

中添加包名
<init-param> 
    <!-- For Jersey 2.x -->
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.ft.resources</param-value>
</init-param>

希望这可以解决您的问题