如何在 grizzly 上使用 jersey 2.0 guice如何在、grizzly、jersey、guice

2023-09-06 15:06:07 作者:猫人妖 #

我想在 Grizzly 上使用 Guice + Jersey 2.0.根据这个 How to use guice-servlet with Jersey 2.0? 讨论 目前 Jersey2 没有直接的 Guice 集成,但可以使用 HK2 作为桥梁来实现.我还检查了 Github 中的示例项目 https://github.com/piersy/jersey2-guice-example-with-test .本项目使用 Jetty 实现.

I want to use Guice + Jersey 2.0 on Grizzly. According to this How to use guice-servlet with Jersey 2.0? discussion there is no direct Guice integration for Jersey2 at present but it can be achieved using HK2 as a bridge. I also checked the sample project in Github https://github.com/piersy/jersey2-guice-example-with-test . This project is implemented using Jetty.

但我的问题是在 Grizzly 中实现它.在 Jetty 上是这样使用的

But my problem is to implement it in Grizzly. On Jetty it is used like this

  @Inject
public MyApplication(ServiceLocator serviceLocator) {
    // Set package to look for resources in
    packages("example.jersey");

    System.out.println("Registering injectables...");

    GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);

    GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(Main.injector);

}

我对 grizzly 的问题是,如何获取这个 serviceLocator 对象?

My problem on grizzly is , how to get this serviceLocator object?

谢谢.

推荐答案

我在这里创建了示例https://github.com/oleksiys/samples/tree/master/jersey2-guice-example-with-test

Grizzly 初始化代码如下所示:

The Grizzly initialization code looks like this:

final URI uri = UriBuilder.fromUri("http://127.0.0.1/")
        .port(8080).build();

// Create HttpServer
final HttpServer serverLocal = GrizzlyHttpServerFactory.createHttpServer(uri, false);

// Create Web application context
final WebappContext context = new WebappContext("Guice Webapp sample", "");

context.addListener(example.jersey.Main.class);

// Initialize and register Jersey ServletContainer
final ServletRegistration servletRegistration =
        context.addServlet("ServletContainer", ServletContainer.class);
servletRegistration.addMapping("/*");
servletRegistration.setInitParameter("javax.ws.rs.Application",
        "example.jersey.MyApplication");

// Initialize and register GuiceFilter
final FilterRegistration registration =
        context.addFilter("GuiceFilter", GuiceFilter.class);
registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), "/*");

context.deploy(serverLocal);

serverLocal.start();
 
精彩推荐
图片推荐