1

我在使用 Jersey 设计 REST 微服务时遇到了 22 个问题。我正在尝试创建一个带有嵌入式灰熊服务器的应用程序以降低部署复杂性。因此,我有一个创建灰熊服务器的主要方法。我需要在服务器的引导过程之前注入一些对象。

我的主要看起来像这样:

public static void main(String[] args) {
    App app = new App(new MyResourceConfig());
    // Need to inject app here.
    app.init(args);
    app.start();        
}

如何获取ServiceLocator单例实例以便注入我的应用程序对象?

我试过了:

ServiceLocatorFactory.getInstance()
                     .create("whatever")
                     .inject(app);

但是,我需要将所有内容绑定AbstractBinder到它上两次(因为我已经在我的ResourceConfig.

4

2 回答 2

1

将所有你绑定AbstractBinderServiceLocator你正在创建的,然后将该定位器传递给 Grizzly 服务器创建工厂方法之一。这将是 Jersey 将从中提取所有服务并将它们粘贴到另一个定位器中的父定位器。例如像

ServiceLocator serviceLocator = SLF.getInstance().create(...);
ServiceLocatorUtilities.bind(serviceLocator, new Binder1(), new Binder2());
App app = new App();
serviceLocator.inject(app);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(
        URI.create(BASE_URI),
        resourceConfig, 
        serviceLocator
);

你需要确保你有 Jersey-Grizzly 依赖,而不仅仅是 Grizzly。

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
</dependency> 

也可以看看:

笔记:

如果您尝试使用 来创建一个 Grizzly servlet 容器GrizzlyWebContainerFactory,那么尝试进行上述工作将会很困难。没有工厂方法可以传递定位器。Jersey 确实添加了对属性的支持ServletProperties.SERVICE_LOCATOR,但即便如此,属性值也应该是 a ServiceLocator。grizzly servlet 容器的工厂方法只接受Map<String, String>init-params。此属性实际上是由使用 Jetty 嵌入式的第三方贡献者添加的,该贡献者确实具有将值设置为对象的 init-params 方法。因此,如果您需要对此的支持,您可能需要向 Jersey 提出问题。

于 2015-11-19T02:34:44.560 回答
1

为了扩展@peeskillet 的出色答案,在我的场景中,我不得不将我的 Jersey 应用程序与其他 servlet 一起部署在同一个 Grizzly servlet 容器中,实际上,这有点痛苦。

但是后来我发现了https://github.com/jersey/jersey/pull/128这节省了我的时间。看着那个拉取请求,这就是我想出的:

WebappContext webappContext = new WebappContext("myWebappContext");

webappContext.addListener(new ServletContextListener() {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        sce.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, MY_SERVICE_LOCATOR);
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) { }
});

ServletRegistration servlet = webappContext.addServlet("myAppplication", new ServletContainer(resourceConfig));
servlet.addMapping("/application/*");

ServletRegistration hello = webappContext.addServlet("myServlet", MyServlet.class);
hello.addMapping("/servlet/*");

HttpServer createHttpServer = GrizzlyHttpServerFactory.createHttpServer(MY_URI, false);
webappContext.deploy(createHttpServer);
createHttpServer.start();
于 2016-11-27T18:09:08.077 回答