How to use jersey 2.0 guice on grizzly

倾然丶 夕夏残阳落幕 提交于 2019-11-29 10:48:57

I have created the sample here https://github.com/oleksiys/samples/tree/master/jersey2-guice-example-with-test

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

add dependecy

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

create feature

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;
    }
}

register feature

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(GuiceFeature.class);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!