How to use the Jersey 2.0 Whistle on a grizzly

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

But my problem is to implement it in Grizzly. On Jetty, it is used as follows

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

My grizzly problem is how to get this serviceLocator object?

Thanks.

+6
source share
2 answers

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

Grizzly's initialization code is as follows:

 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(); 
+5
source

add dependecy

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

create function

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

registration function

 ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register(GuiceFeature.class); 
+1
source

Source: https://habr.com/ru/post/951129/


All Articles