簡體   English   中英

如何在嵌入式 Grizzly Jersey 應用程序的 main 方法中使用 HK2 注入對象

[英]How to inject object with HK2 in main method in a embedded Grizzly Jersey application

在使用 Jersey 設計 REST 微服務時,我遇到了一個 catch 22 問題。 我正在嘗試創建一個帶有嵌入式 Grizzly 服務器的應用程序,以降低部署復雜性。 因此,我有一個創建灰熊服務器的主要方法。 我需要在服務器的引導程序之前注入一些對象。

我的主要看起來像這樣:

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這樣做了)。

將所有AbstractBinder綁定到您正在創建的ServiceLocator ,然后將該定位器傳遞給 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> 

也可以看看:

筆記:

如果您嘗試使用GrizzlyWebContainerFactory創建 Grizzly servlet 容器,則嘗試進行上述工作將很困難。 沒有傳遞定位器的工廠方法。 Jersey 確實通過屬性ServletProperties.SERVICE_LOCATOR添加了支持,但即使如此,屬性值也應該是ServiceLocator grizzly servlet 容器的工廠方法只接受Map<String, String>作為 init-params。 該屬性實際上是由使用嵌入的 Jetty 的第三方貢獻者添加的,該貢獻者確實具有使用值作為對象設置 init-params 的方法。 因此,如果您需要對此的支持,您可能需要向 Jersey 提交問題。

為了擴展來自@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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM