1

Jersey を使用して REST マイクロ サービスを設計しているときに、catch 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);

ただし、すべてを 2 回バインドする必要がありますAbstractBinder(既に で実行しているためResourceConfig)。

4

2 に答える 2

1

@peeskillet からの優れた回答を拡張するには、私のシナリオでは、Jersey アプリケーションを同じ Grizzly サーブレット コンテナー内の他のサーブレットと共にデプロイする必要がありましたが、実際には少し面倒でした。

しかし、その後、私の一日を救った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 に答える