bootstrap Jersey 2(使用 Jetty)的正确方法是什么?

What's the right way to bootstrap Jersey 2 (with Jetty)?

我已经成功破解了 HK2 注入的工作 Jersey/Jetty 设置,但考虑到我发现的大量有点令人困惑(有时不一致)的文档,我不是确定我是否错过了正确处理的一些重要细节。就目前而言,我正在像这样引导 servlet;

        // Jersey
        ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        ServletContainer jerseyServletContainer = new ServletContainer(new AppResourceConfig());
        ServletHolder jerseyServletHolder = new ServletHolder(jerseyServletContainer);
        servletContextHandler.setContextPath("/");
        servletContextHandler.addServlet(jerseyServletHolder, "/api/*");

        // Wire up Jetty
        HandlerCollection handlerList = new HandlerCollection();
        handlerList.setHandlers(new Handler[]{ servletContextHandler });
        Server server = new Server(configuration.getInt("Server.Port"));
        server.setHandler(handlerList);
        server.start();
        server.join();

我将 AppResourceConfig 定义为;

public class AppResourceConfig extends ResourceConfig {
    public AppResourceConfig() {
        register(new AppBinder());
        packages("org.sandbox.resources");
    }
}

我的 AppBinder 为;

public class AppBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(new StringService()).to(StringService.class);
    }
}

这一切都适用于我的简单测试用例,但我不清楚有几件事。 Jersey 文档引用了我应该扩展的应用程序 class,并使用 Injections.addBinding 设置了绑定。然而,为了做到这一点,他们以某种方式使用 @Inject 将 ServiceLocator 实例获取到他们的构造函数中。然后他们似乎根本没有创建活页夹? (https://jersey.java.net/documentation/latest/migration.html -- 26.14.1.1。注入自定义对象)。

有人可以阐明我的方法是否正确,也许可以启发我 Application 和 ResourceConfig 之间的区别,以及我实际上应该做什么才能与框架的意图保持一致?

Application is part of JAX-RS, the REST API defined by Java EE specifications. Jersey is one implementations of that API. You therefore can use the standard Application to set up REST applications with Jersey, as defined by JAX-RS. ResourceConfig 扩展了 Application 并且是 Jersey 的特定实现增强。它允许更轻松的设置,例如添加注入或添加要扫描的包,就像您在代码中所做的那样。

链接的文档确实使用了活页夹。没有的例子指的是旧球衣 1.x。我认为其他示例使用 org.glassfish.jersey.internal.inject.Injections class ,这是(正如包名称所暗示的)不应使用的 internal class 。我不知道他们为什么将其包含在文档中,它认为不应该存在。也许它曾经是 public API 的一部分,或者没有其他方法可以完成示例。无论如何,最好不要使用 class.

你的方法看起来不错。使用 Jersey API 的特性而不是将自己局限于纯 JAX-RS 会使容器环境中的应用程序 运行 变得更加困难,如果它们只提供其他 JAX-RS 框架,如 RestEasy 或 Apache CFX。如果您不打算支持其他框架,那么利用 Jersey 的优势是必经之路。