如何在灰熊上使用球衣2.0 guice

时间:2013-08-06 12:58:53

标签: jersey guice grizzly

我想在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实现。

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

  @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对象?

谢谢。

2 个答案:

答案 0 :(得分:5)

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

Grizzly初始化代码如下所示:

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();

答案 1 :(得分:1)

添加依赖性

compile group: "org.glassfish.hk2", name: "guice-bridge", version: "2.4.0"

创建功能

public class GuiceFeature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        ServiceLocator serviceLocator = ServiceLocatorProvider.getServiceLocator(context);

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);

        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(YYY.class).to(ZZZ.class);
            }
        });
        guiceBridge.bridgeGuiceInjector(injector);

        return true;
    }
}

注册功能

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(GuiceFeature.class);